The connection math nobody does before putting Mongo behind Lambda

At 14:25 an alert told me our MongoDB cluster was above 90% of its connection limit, current value 95.8%.

My first thought was the boring one. We had grown, the cluster was too small for us, someone should click the upgrade button and we could argue about the bill afterwards. That thought lasted about ten minutes, which is how long it took me to stop reading the cluster-level number and open the per-node breakdown.

The cluster had three nodes. One of them was pinned at 1,450 to 1,500 connections. The other two sat at around 209 each, serving something like six queries a second between them. We had not run out of connections. We had run out of connections on one third of the hardware, while the other two thirds did nothing.

Reading the topology off the metrics

You can tell which node is the primary without opening a console. Look at the write rates.

The saturated node was serving 95 to 280 inserts per second, a similar number of updates, and 500 to 1,200 commands per second. The other two showed almost no inserts and almost no updates. In a MongoDB replica set, only one node accepts writes; the others replay those writes from the replication log. So whichever node shows insert and update throughput is the primary, and the rest are secondaries.

That is a small trick, and it reframed the whole incident for me. The question stopped being how many connections we needed and became why every connection was pointed at a single node.

The answer is that the MongoDB driver defaults to readPreference=primary. Not primaryPreferred, not nearest. Primary. Unless you say otherwise, every find and every aggregation from every one of your services goes to the same node that is absorbing all the writes, and queues behind them. The secondaries are up, they are replicating, and they are serving almost nothing.

We had never said otherwise anywhere in our code.

What saturation looks like from the client

I want to spell out the failure signature, because it does not announce itself as a connection limit. It arrives dressed as a network problem.

When the node reaches its cap it stops completing new TLS handshakes. It does not send back a useful error. It accepts the TCP connection and then drops it before the negotiation finishes, so what the client sees is this:

MongoNetworkError: Client network socket disconnected
before secure TLS connection was established

That reads like a transient network fault. It is a capacity limit.

Then the driver does the correct thing and makes it worse. When an operation fails on a connection, the driver clears the entire pool for that server, on the theory that if one socket to a server is broken, the rest probably are too. Clearing the pool fails every operation currently in flight on it:

PoolClearedError: Connection pool for <host> was cleared
because another operation failed

Those failures reach the Lambda invocations, the invocations fail, the queue redelivers the messages, Lambda starts more containers to absorb the redeliveries, each new container builds a fresh connection pool, and every one of those connections needs a TLS handshake from a node that already cannot finish the handshakes it has. The retry path is now the load generator.

In the two hours before the alarm evaluated, roughly 5,000 Lambda events failed. Two queue-driven consumers accounted for nearly all of it, 2,543 from one and 2,375 from the other. Inside that, 2,204 were socket-disconnected-before-TLS and 1,786 were the pool-cleared cascade behind them. The second number is the interesting one. The driver's reaction to the refusal did more than a third of the damage on its own.

We sent the reads to the machines that were doing nothing

We changed the read preference on the read-heavy consumers to secondaryPreferred and deployed. Then I watched the per-node connection graph, and I have rarely seen a production graph move like that.

MinutePrimaryEach secondary
01,500209
11,485254
21,475461
31,354804
41,207846
51,171835

The primary's query rate went from about 28 per second to about 6. Each secondary went from about 2 per second to about 40. Four minutes from deploy to a primary that was no longer against the ceiling, and we added exactly zero capacity.

We already owned two idle machines and had never told the driver they existed.

What you pay for that is read-your-own-write consistency. A secondary trails the primary by the replication lag, usually milliseconds, occasionally more. A consumer that reads a record to enrich an event can live with that. A flow that writes a document and immediately reads it back expecting to see its own write cannot. So this is a decision per consumer, not a flag on the shared connection string. We changed it where the read tolerated staleness and left it alone where it did not.

The arithmetic that made it inevitable

The canonical advice about running Mongo behind serverless functions stops one step too early.

Everyone knows to create the client once at module scope so it is reused across invocations of the same container. That advice is correct and it is nowhere near sufficient, because it only controls one of the two numbers that matter. It reduces connections per container, which is the number maxPoolSize caps. It says nothing about how many containers you have.

The footprint on your cluster is:

connections = sum over all functions of
              (concurrent containers) x (maxPoolSize)

A function with reserved concurrency of 100, meaning AWS will run up to 100 copies of it at the same time, and the driver's default maxPoolSize of 100, can ask for 10,000 connections on its own. Against a node that stops accepting them at 1,500. Lambda hands you that concurrency without complaint, because Lambda has no idea your database has a ceiling.

The rule we wrote down afterwards:

(reserved concurrency) x (maxPoolSize) <= 0.6 x (cluster connection cap)

Sixty percent rather than a hundred, because you need headroom for the long-running services, the migration scripts, whoever has a shell open, and the reconnection storm that follows a failover. Before the incident, that product summed to more than 1.0 times the cap. On paper we had already promised the cluster more connections than it could ever accept. It held together only because the functions never all ran at once, until one day they did.

Six client options and why each one is there

The config we landed on is short. Every line in it exists because something specific broke.

const client = new MongoClient(uri, {
  maxPoolSize: 5,
  minPoolSize: 0,
  maxIdleTimeMS: 60000,
  serverSelectionTimeoutMS: 10000,
  retryWrites: true,
  readPreference: 'secondaryPreferred',
});

maxPoolSize: 5 is deliberately small. In a long-lived server a pool of 5 would be stingy. In Lambda the pool is multiplied by the container count, so the per-container ceiling has to be small for the global budget to fit. minPoolSize: 0 because a container that is warm but idle should hold nothing open.

maxIdleTimeMS: 60000 is about the network rather than about Mongo. A NAT gateway drops idle TCP flows after somewhere around 350 seconds. It does not send a reset, it just stops forwarding, so both ends still believe they have a socket. If the driver keeps a connection idle past that window, the next checkout writes into a half-open socket, gets a failure, and clears the pool. Closing at 60 seconds guarantees the next checkout opens a fresh connection instead.

serverSelectionTimeoutMS: 10000 has to satisfy two deadlines at once. Replica set elections typically resolve in 8 to 12 seconds. The driver default of 30 seconds holds the invocation hostage well past the queue's visibility timeout, which is the window during which SQS hides a message from other consumers while one works on it. Once that expires the message is redelivered while the original invocation is still sitting there waiting, and now the same work runs twice. Five seconds is too aggressive and fails during ordinary failovers. Ten seconds rides out a normal election and still fails the batch fast enough for the queue to retry cleanly.

retryWrites: true and the read preference pull in the same direction. retryWrites survives a single dropped write during a failover instead of failing the batch. The read preference keeps the batch off the node most likely to be failing over.

There is a seventh thing, and it is not an option at all. Our connection URI carries temporary credentials with a six-hour expiry. A module-scope singleton cached forever keeps working right up until the credentials expire underneath it, and then every invocation on that warm container fails authentication while a cold one succeeds, which is a delightful thing to debug. We tear the client down and rebuild it every four hours. "Cache the client forever" is wrong the moment your connection string has an expiry date in it.

The alarm was the last thing to notice

The alert fired at 14:25. The error pattern had been in the logs since at least 13:03.

The alarm condition was 90% sustained for five minutes. That is a reasonable threshold for a metric that climbs. It is a poor one for a metric that plateaus, because a connection count does not pass through 90% on its way somewhere higher. It slams into the cap and flattens. By the time the average crosses 90% and stays there for five minutes, you have already been failing for over an hour. We moved the threshold to 75% and added a rate-of-change alarm next to it.

The last thing I wrote in the notes is the one I would keep if I could only keep one. We opened the investigation by looking up the published connection limit for our cluster tier and arguing about whether it applied to us. That was wasted time. The 1,500 plateau was drawn on our own graph, flat as a table edge, for two hours. The ceiling had already told us where it was. We went looking for it in the documentation first.