Before I begin let me note that I've already read these resources:
MongoDB Cloud Deployment - High TTFB
https://mongoosejs.com/docs/connections
I'm running a Node.js app that connects to a Mongo database on an AWS EC2 instance. The Node.js app and the database are on the same server. The instance is a Windows server running IIS and I use IISNode to connect to the app. I live close to the region where my EC2 instance is being hosted.
I use Mongoose to connect to my database. I'm not using localhost in my connection string; I use the mongodb://127.0.0.1:27017 format.
I experience a 1 to 2 second delay for my TTFB.
Is there a way to resolve this? Is this just a normal delay for an initial connection?
While I'm here I could also use some clarification about how connections and sockets work in MongoDB. If a user connects to the database and there are sockets open on the connection, and a user from a different IP address tries to connect to the database do they use an open socket? I tried to test this using a VPN but I was uncertain about the results.
Thanks ahead of time for your help.
I came up with a solution which may be a little bit hack but it works. If anyone has a better solution feel free to post it.
I'm using a front end web application that allows queries to the database. I added some code to the front end application so that when the page loads a query is sent to the database:
$(document).ready(function() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL-for-an-empty-record-in-your-database", true);
xhttp.send()
})
I then made sure the correct CORS headers were added to my Node.js Express app by adding these lines of code:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'my-frontend-application-url');
res.setHeader('Access-Control-Allow-Methods', 'GET');
next();
});
I included the above code because I had previously been using JSONP to make requests to my Node.js app and when I switched to XHR requests the headers needed to be included. I noticed an increase in the speed of my requests being returned after making this change. Previously, a request would take an average of 300ms to 400ms to return and now they return in around 130ms to 200ms. I also noticed that the time for an initial connection dropped down to 600ms to 800ms; previously it had been 1 to 2 seconds. Because I use a Lambda function the initial request will also begin a cold start (if not already warm) when the front end application loads.