Avoid ECONNRESET error when using Node.js and Rethink DB

lockevn
1 min readFeb 12, 2019

--

Recently, I encounted a random-to-reproduce issue, happens on both the dev machine and production. When my node app runs, it often raises ECONNRESET error, randomly.

Run line by line in debugging, I cannot see the issue.

I guess this is a run-too-fast and race-condition problem (the good old issue when you write multi-threading app in .NET or Java).

IMO, RethinkDB server will refuse connection, if you connect too fast, or make to much connections in short time.

In my case, instead of throttling, I make the RethinkInstance.js like “singleton”, use Rethink.js (which is my lib, wrapped Rethink JS API)

```
const { Rethink } = require(“@lockevn/lib-core”);

// … any one time initialization goes here …

var rethinkConfig = require(“../_secret/.rethinkdb.jsonconfig”);
var xcRethink = new Rethink(rethinkConfig);
xcRethink.getConnection();

export default xcRethink;
```

WARNING: there is no singleton pattern in Node.js.

this file implements the singleton alike pattern here

https://basarat.gitbooks.io/typescript/docs/tips/singleton.html

We only want one instance of Rethink object, connect to the DB

because (in production, or without debugging breakpoint hit) if we create object too fast, create connection to fast, it raises ECONNRESET error

I discover this because when I debug and trace, the ECONNRESET does not happen

See more about “Singleton” here https://stackoverflow.com/questions/13179109/singleton-pattern-in-nodejs-is-it-needed

--

--

lockevn
lockevn

Written by lockevn

Developer, Sportman. Write code with joy, bake app with heart. Opinions are my own. If you feel I save your time, go http://BuyMeACoff.ee/Lockevn

No responses yet