Don’t dread the Thread, it’s just Java async code

Posted on Leave a comment

I grew up with a fear of Java Threads. It was a time when Java and C# were the only “serious” programming languages to be used to write enterprise software. This was especially true in India, which to date remains a laggard in terms of technology adoption. The concept of Threads was hard enough for a budding programmer. And to make matters worse, the Thread API was far from being intuitive. Concurrency, deadlocks, semaphores, and synchronization were topics that were thrown around as stone pelters throw stones on anyone approaching their territory.

The concept of async code in other languages seemed equally mind-bending at first. During the Web 2.0 days, creating dynamic interfaces via Ajax was cool but it forced one to understand async code flow in JavaScript. Somehow, JS (or more precisely, jQuery) managed to make async code not as hard to understand as Threads in Java. Yet, at a grassroots level, both did the same thing—allow developers to write non-blocking code.

Reading the chapter on Concurrency in the book The Pragmatic Programmer triggered this comparison in my head. Having worked on professional software for over 12 years in several different languages, async code now feels intuitive. Back then, it was hard. Threads were hard. Not only would I skip reasoning about potential concurrency issues in my software, I would also leave out without flinching any discussion about concurrency or threads in reference material. Surely threads were designed to be used in “very complex” applications, something that I would not be doing until my late thirties. Hah!

It’s only now that I realize concurrency is unavoidable—it’s implicitly baked into so many daily problems that not thinking about concurrency means knowingly or unknowingly creating software that would not scale to survive the harshness of the real world.

So, here I am writing a note to my younger self:

It’s useful to think of threads simply in terms of tools that provide the ability to execute pieces of code asynchronously. Before asyncawait and Future , the only way to run async code in Java was to use a Thread. In short, a thread is just Java async code.

Node.js made it super-easy to run async code via callbacks, so much so that it became a preferred standard when writing I/O heavy code. So, programmers who would not write async or non-blocking code in Java due to the fear of threads could easily do so in Node.

Prevent Redis client from crashing your Node.js app

Posted on 1 Comment


Redis is a high-performance in-memory database that is often used for data caching on server-side. The redis npm package makes is nice & easy to use Redis to cache data in a Node app. If you are new to Redis, you will find this tutorial on Coligo helpful in implementing data caching in your own application. It often results in 10x or more performance increase. Don’t take my work, check it out yourself!

An annoying issue with the redis package is that, if Redis server is not running, doing this emits an uncaught exception, crashing the whole app:

redisClient = redis.createClient();

As this operation, like most operations in Node, is asynchronous, using try-catch simply doesn’t work.

My solution is to create a singleton Redis client instance that handles the Redis-server-not-running case through its retry_strategy option. When Redis server is not running, my singleton returns a fake Redis client that has same function names as the real Redis client. This gives me the benefit of using redis package’s code the way it’s advertised on its documentation without any additional error handling code and without worrying about whether Redis server is running.

I hope my code helps you too. Just create a file redisClient.js somewhere in your Node app and require it when you need to use it.

var redisClient = require('common/redisClient');
var redis = redisClient.getClient();
redis.setex(unique_key_name, 60, data_to_be_cached);


// Singleton for Redis cache database client.
// @file: redisClient.js
// @author: Anurag Bhandari
var redis = require('redis');
var redisClient = (function () {
    // Start with a fake client so that we have a client that works
    // even when Redis server is down
    var client = {
        get: function (key, cb) {
            cb(null, null);
        setex: function (key, time, value) {
            // Do nothing in particular
    // Attempt to create a new instance of an actual redis client
    var connectionString = process.env.REDIS_URL || 'redis://localhost:6379';
    var c = redis.createClient(connectionString, {
        retry_strategy: function (options) {
            if (options.error.code === 'ECONNREFUSED') {
                // This will suppress the ECONNREFUSED unhandled exception
                // that results in app crash
    // Set the "client" variable to the actual redis client instance
    // once a connection is established with the Redis server
    c.on('ready', function () {
        client = c;
     * Get a redis client
     * @return {Object} client - eventually a proper redis client object (if redis is up) or a fake client object (if redis is down)
    var getClient = function () {
        return client;
    return {
        getClient: getClient
module.exports = redisClient;

Authentication for your Node/Express based APIs

Posted on Leave a comment

This post is not a tutorial, just some thoughts on the topic. There are plenty of tutorials out there that talk about protecting your RESTful Node/Express based APIs using some form of token-based authentication. Some of them are pretty straightforward to follow, some not. But most of them have one thing in common — delegating the authentication part to Passport.js. While that’s not a bad idea, using Passport.js for anything other than basic HTTP authentication can be bewildering, especially when you want to implement a more secure auth such as OAuth or HTTP Bearer.

HTTP Basic Authentication is a big NO-NO

Never, ever think of doing this just for the sake of making it easy to call your APIs from client-side code. Basic authentication is insecure. Period. It’s way too easy to crack.

Start with a simple JWT-based Token Authentication


JWT has pretty much become the standard auth token format. It’s used by small to large enterprises alike. Before actually taking the dive, it will immensely help to understand the anatomy of JWT. Once you’ve done that, give this tutorial a read. It’s one of the best and easy to follow tutorials I’ve come across on this topic.

TL;DR — JWT is a self-contained piece of information. It makes session-based auth a thing of the past. No more creating database tables to store user sessions and no more writing server-side logic to handle them. jsonwebtoken npm package makes it easy to integrate a JWT-based auth flow in a Node/Express based application. Most of the magic happens in your API router’s middleware, which acts as the single place to authenticate ALL your APIs.

Use bcrypt for storing hashed passwords


If you’ve gotten this far in this post, I’m sure you know to NEVER STORE PASSWORDS IN PLAIN TEXT. People have amazing theories. Some n00bs make the mistake of storing plain text passwords, thinking that modern database systems are themselves secure enough and unhackable. They are totally wrong. Yes, database vendors like Oracle and Microsoft do their best to make their systems highly secure and robust but what good is that security when the app itself is stupidly vulnerable?

Developers who realize this bit actually store passwords as irreversible hashes, sometimes relying on good ol’ MD5 or SHA-1 algorithms. But even these aren’t secure enough. There are better and more secure hashing algorithms, such as bcrypt. I’ve found the bcrypt-nodejs npm package to be pretty straightforward.