Avatar
Nguyễn Chánh Đang
icon
icon
22/8/2026

Engineering Scalable Full-Stack Architecture with Next.js and MongoDB

High-Performance Serverless MongoDB

Connecting Node.js/Next.js serverless functions to a database requires careful connection lifecycle management to avoid connection exhaustion and high latency spikes.

Connection Reuse Pattern

In serverless environments, module-level caching ensures instances reuse existing client connections across warm invocations:

import { MongoClient } from "mongodb";

const options = {
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
};

let clientPromise: Promise<MongoClient>;

if (process.env.NODE_ENV === "development") {
  if (!global._mongoClientPromise) {
    const client = new MongoClient(process.env.MONGODB_URI!, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  const client = new MongoClient(process.env.MONGODB_URI!, options);
  clientPromise = client.connect();
}

export default clientPromise;

Key Optimization Principles

  • Projection Optimization: Only query fields required for the view.
  • Compound Indexes: Create compound indexes on frequently sorted and filtered fields like { isPublished: 1, createdAt: -1 }.
  • Normalization Helpers: Standardize document _id to string id at the database adapter layer to ensure type safety.
© 2025 Chánh Đang. All rights reserved.
Inspired by
Dracula Theme Logo
&&