MongoSocketReadException: Prematurely reached end of stream (after a period of inactivity)

Rhangaun picture Rhangaun · Aug 22, 2016 · Viewed 55.4k times · Source

I get this error on a find call (default Java Driver) after a period of inactivity. I tried to add a manual heartbeat (writing to a capped collection), but it didn't help. I only get the issue while being connected to an instance on compose (i.e. not in a local context).

MongoDB version is 3.2.8, latest driver (3.3), using Java 8.

Any idea ?

Answer

Sachin picture Sachin · Sep 7, 2016

I found it in some documentation:

For long running applications, it is often prudent to enable "keepAlive" with a number of milliseconds. Without it, after some period of time you may start to see "connection closed" errors for what seems like no reason.

Check if this helps. When you connect to mongoDB you can pass socket options to it. I am from node background we use following options to keep it alive.

server: {
        socketOptions: {
            keepAlive: 100,
            connectTimeoutMS: 30000
        }
    }

Hope this helps!!