Everyday Software Design Patterns

If you write software, you use design patterns knowingly or unknowingly. If we learn principles we use instead of just learning how the framework works, life can be little simpler.

Lets take a look at some of the very very basic examples that you would have used.

Example 1: Database connection with Node.js and Hapi

Lets say your server is connecting to the database. Its working fine and this is how your config/config.js

Now lets change the database name without restarting the node server

Now if we hit the server, what do we expect? Should our server responds with the error or with the response as if nothing has happened?

The correct answer is that the server would respond as if nothing has changed. Looks like the database connection is made when the server starts. If we think about it a little more it makes sense as making connection to db is expensive. Looks like Singleton pattern is used here.

Example 2: Memory leak in Node.js

Lets take a look at this code

Memory leak example

All this code does is whenever a request is made to <host:3000>, its starts pushing an array into myBigFatArray. Lets try and simulate this server to a production server where you receive multiple request with many concurrent users. To do this we will use Apache Benchmark. We use the following commands:

Start server: node server.js

Start apache benchmark: ab -n 30000 -c 20 http://127.0.0.1:3000/

While running the benchmark you would eventually run out of memory and get this error

If we look at this problem, we will realize that the problem is our myBigFatArray. Looks like it is initialized once the lifetime of the server. If it would have been inside the handler , it would have been just fine as GC would have cleaned it up upon the end of each request. Another simple example of Singleton pattern.

There are some other patterns that are commonly used like Observer and Module but one pattern at a time

--

--

Senior Staff Engineer @freshworks. Ex-McKinsey/Microsoft/Slideshare/SAP, Tech Enthusiast, Passionate about India. Opinions are mine

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhinav Dhasmana

Senior Staff Engineer @freshworks. Ex-McKinsey/Microsoft/Slideshare/SAP, Tech Enthusiast, Passionate about India. Opinions are mine