javascriptnode.jsmongodbastrojs

How does Astro Close Database Connections?


I am not sure on how or if Astro closes database connections upon retrieval of data. Is it that the packages themselves take care of this or the connections "just" drop and it is up to the database server at the other end to timeout and close them?

Examples: Supabase as a backend service: https://docs.astro.build/en/guides/backend/supabase/ do not see any closing of database connections. Same on Astro DB: https://docs.astro.build/en/guides/astro-db/ plus in a codebase I saw with Mongo (not official): https://github.com/skolhustick/astro-mongodb/blob/main/src/lib/mongodb.js where for example the user retrieval here: https://github.com/skolhustick/astro-mongodb/blob/main/src/pages/users/index.astro "only" retrieves but never closes the connection.

I see code like this everywhere:

---
import { getAllUsers } from "../../lib/users";
import Layout from "../layouts/Layout.astro";
const users = await getAllUsers();
if (!users) {
  return new Response(null, {
    status: 404,
    statusText: "Not found",
  });
}
---

/* and in users.js */
import { Users } from "./mongodb";

export const getAllUsers = async () => {
  const users = await (await Users()).find({}).toArray();
  return users;
};

export const createUser = async (newUser) => {
  const user = await (await Users()).insert(newUser);
  return user;
};

So yes, my question is this: does Astro "never" close connections? Should it? Should developers add something, or do the underlying npm packages take care of it when the process ends?

Possible related: When to close MongoDB database connection in Nodejs


Solution

  • This depends on the environment you're running Astro in:

    1. For server-side-rendering on the "edge" or in a so-called "serverless" environment (e.g. Cloudflare workers, AWS Lambda etc), you could use something like Supabase, which for example comes with its own connection-pooler that manages this for you.

    2. For server-side-rendering in a traditional long-running Node.js process, you will want to reuse the db-connection across several http-requests to your server. There, you'd usually close the db connection only on server shutdown.

    3. For Static Content Generation, you could of course close the connection when generation is done. But unless you have dozens of static site generation jobs running at the same time, and/or your database server has strict connection limits, you are unlikely to run into problem with not closing the connection. The database server will have a timeout and eventually close the connection on its end.

    Note that details will also depend on the database and the database driver.