Quick Docker and MongoDB replica set on your computer

I’m not here to teach you anything really, just provide you a quick way to achieve a simple result: make a MongoDB replica set out of a very simple local MongoDB docker deployment.

In this specific scenario, I’m not aiming to a super complete configuration, for which you will probably want to introduce a mounted configuration directory etc. Instead, I am interested in getting the bare minimum started for testing purposes. This specific need came up in development and I wanted to observe the software behaviour during a primary server step down and restore.

Before we start:

  • we are going to use docker-compose
  • we are going to spin everything on one server, which defeats the purpose of a replica set, but it’s good enough for our testing purposes

First off, we’ll need the docker-compose file, so we don’t end up playing too much with the terminal.

version: '2'

    image: mongo:3.0.14
    hostname: mongo.myrepl
            - mongo.myrepl
    - --storageEngine
    - wiredTiger
    - --replSet
    - myrepl
      - mongo-2
      - mongo-3

    image: mongo:3.0.14
    hostname: mongo-2.myrepl
            - mongo-2.myrepl  
    - --storageEngine
    - wiredTiger
    - --replSet
    - myrepl
    image: mongo:3.0.14
    hostname: mongo-3.myrepl
            - mongo-3.myrepl
    - --storageEngine
    - wiredTiger
    - --replSet
    - myrepl

We can start all this docker-compose file as a whole by issuing the famous: sudo docker-compose up -d.

We can check the instances are up and running by issuing the sudo docker-compose ps command. It should output something like:

mongorepl_mongo-2_1 docker-entrypoint.sh --sto ... Up>27017/tcp 
mongorepl_mongo-3_1 docker-entrypoint.sh --sto ... Up>27017/tcp 
mongorepl_mongo_1 docker-entrypoint.sh --sto ... Up>27017/tcp


  • I’m using mongo 3.0.14 because… I had it in the computer I’m using right now and didn’t have HDD space to download another one. A more recent version should pretty much work the same way.

All three instances are declared to belong to the “myrepl” replica set, but we need to initialize it before it can actually be used. In this state, the mongo instances believe to be standalone.

To initiate replication, I decided to do everything with a one-liner, because it’s how true heroes do it.

Here it is:

sudo docker exec -i -t mongorepl_mongo_1 mongo localhost --eval "rs.initiate();rs.add('mongo-2.myrepl');rs.addArb('mongo-3.myrepl');"

In this command, I’m launching the mongo client in the first mongo instance. The name of the instance (mongorepl_mongo_1) has been generated by docker-compose, chaining the directory name and the name of the service. You can easily find yours by invoking a sudo docker-compose ps.

The command initiates the replica set and then adds mongo-2.repl as a regular member of the replica set and mongo-3.repl as an arbiter. If you’re not familiar with the concept of arbiter, I suggest you dig a little deeper here https://docs.mongodb.com/manual/core/replica-set-arbiter/

Next we can check whether our command actually worked by connecting to supposed primary:

sudo docker exec -i -t mongorepl_mongo_1 mongo

The shell should welcome you with the prompt: myrepl:PRIMARY>  which is a strong hint that things are quite right.

In the mongo shell, we can finally issue an rs.status() command that should print something like:

	"set" : "myrepl",
	"date" : ISODate("2018-07-17T12:16:02.168Z"),
	"myState" : 1,
	"members" : [
			"_id" : 0,
			"name" : "mongo.myrepl:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 186,
			"optime" : Timestamp(1531829584, 4),
			"optimeDate" : ISODate("2018-07-17T12:13:04Z"),
			"electionTime" : Timestamp(1531829584, 2),
			"electionDate" : ISODate("2018-07-17T12:13:04Z"),
			"configVersion" : 3,
			"self" : true
			"_id" : 1,
			"name" : "mongo-2.myrepl:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 177,
			"optime" : Timestamp(1531829584, 4),
			"optimeDate" : ISODate("2018-07-17T12:13:04Z"),
			"lastHeartbeat" : ISODate("2018-07-17T12:16:00.975Z"),
			"lastHeartbeatRecv" : ISODate("2018-07-17T12:16:01.121Z"),
			"pingMs" : 0,
			"configVersion" : 3
			"_id" : 2,
			"name" : "mongo-3.myrepl:27017",
			"health" : 1,
			"state" : 7,
			"stateStr" : "ARBITER",
			"uptime" : 177,
			"lastHeartbeat" : ISODate("2018-07-17T12:16:00.975Z"),
			"lastHeartbeatRecv" : ISODate("2018-07-17T12:16:01.113Z"),
			"pingMs" : 0,
			"configVersion" : 3
	"ok" : 1

Everything seems to be good and ready for our experiments.


6 things I wish I knew before launching a startup

The word startup is not a fancy name for a company in its early stages, it represents a concept.
Seen from the investors point of view, it describes a tool that allows them to mobilize high risk money in lots of small packets of funding that can lead to nothing, or immensely lucrative speculations. Note that the word company does not even appear in my sentence.

From our perspective, the creators, the startup concept represents the loss of all our fears around starting a company. All of us startuppers got dazed by the idea that it would have been fun, painless and risk free. We’ve been – implicitly – told that the necessary money would have appeared in front of us as an endless stream of resources and all we had to do was accomplishing our dreams. Sure, failure is always on the radar, but there really was nothing to worry about.

As an Italian living in Italy, I am used to being suspicious of dream-fulfilling formulas. We as a people, have this encoded in our DNA: nothing comes for free, and no one except your parents gives any amount of fuck about your dreams.
However the American market and optimism really got me drunk pretty quickly.
I didn’t lose my pragmatism though, and when we got all started, I wanted everything to be set up as a lucrative company, not a fluffy dream. Business plan, product, go-to-market strategy, all that. I wanted to live off someone else’s money for the time needed, but not one minute more.

Little I knew of what was coming next! So here’s 6 things I wish I knew before creating a startup:

1. Invest time and sweat researching your future customers

Most startup products come from direct observation of unsolved problems. In your workplace, in your daily life, in your spare time.
Be humble enough to realize you’ve seen a tiny fraction of the world around you. Sure the problem is real, but it may manifest itself in a completely different configuration in other workplaces, families, countries.
Before even facing your market, make sure all your assumptions on what your future market needs are broad enough for a large subset of contexts, or at least acknowledge whom you’re leaving out of your picture.
The classic process of creating a management software, for example, includes the identification (and employment, if necessary) of a domain expert, the person with all the truths in her sleeve.
Whether you are the domain expert, or are capable of becoming the domain expert, or a buddy of yours can be, make sure you can master the domain in most of its incarnations.

Understand that innovation needs to work with real users’ familiarity with certain concepts. Unless you’re inventing something completely unseen before, make sure your domain expert explains to you what the current expectations are, and accepts your innovations with enthusiasm rather than scepticism.

2. Don’t underestimate the amount of work ahead

Being ready when you join the first sales call is pure utopia. If they’re kind enough, they will get back to you with a lot of observations on what’s “not OK” in what you’re selling. Some of them will look so obvious you will feel dumb.
And it will go on like that for quite some time. So all of a sudden, your shiny roadmap describing the next 2 years of your innovative product,  gets scattered with millions of things that certainly need to be done to meet the here/now expectations.
A good balance between user driven requirements and vision is essential. A strategy will slowly grow in you along the way, but even so the sum of the two can feel overwhelming.

And you’ll overwork, oh yes you will. To the point you’ll be entering your office in the morning and ask yourself “Did I even go home last night…?”.

3. Don’t be too conservative with money

So you have your first round of funding. You then launch your calculator app and start crunching ballpark numbers. Sooner rather than later, you’ll find yourself reducing costs at the very minimum to expand the life span of the company (assuming revenue will not flow in).
While this is wise, and many startups fail being reasonable with expenses, you need to clearly identify which expenses are not necessary, and which on the contrary are necessary.
NEVER cut on necessary expenses. NEVER, delay hiring someone you need because you’re acting conservative. This is a price you will pay later, and very dearly.
Sometimes delaying certain expenses delay success and a delay could ruin your timing to market. Running a three legged company for one more year not only does not guarantee success, but may burn you out because you’re trying to replace the missing leg with your efforts and time.

4. Sloppiness is not an option

When you start you have nothing ready. And when you have nothing ready you rush to get something ready. Sure what you have ready is not perfect, but it kinda works so…
So nothing. One of the most disturbing mistakes you can make is thinking that because you are a startup, customers will be merciful for your incompleteness / bugs / lack of documentation etc.
That is not the case.
Not only being a startup is not an excuse, it’s a obstacle already. You will need to win the prejudice larger companies have toward adopting a software that has been made by a company that may be dead in one year.
So? So invest in perfection. And if you’re too small to do well all the stuff you planned, then remove stuff from your roadmap and do a great job on what you can objectively achieve. If shrinking your roadmap is not an option, then you have a problem to address, but reducing quality is not the way.

5. Beware breakdowns

When you launch your first startup you have no idea what will be of you. Sure it is exciting, and certain media will very kindly show you the bright, adventurous side of it.
But there’s a dark side people rather not talk about.
Furiously overworking. Isolation. Lonely life-changing decision making. Responsibility. Taxes and expenses.  Anxiety. And then you find yourself sighing in the shower asking yourself why you left your OK job for this nightmare.
This happens more frequently than you think and it’s part of the red pill you took.

Breathe. Understand that when you’re close to breaking down, your emotions are amplified. It’s hard to see the world objectively from a roller coaster. So no matter what, no matter how important your duty may seem, stop and take a break. There are very few things in life that can’t wait one day or two, or at least an hour or two. You have no alternative, because if you fall on the ground lifeless, no problem will get solved. And if things are meant to go bad, realize it’s not the end of the world. You are an adventurous person already. The next big thing starts when the previous ends.

6. You’ll be asked to be stone cold

This sucks.
A step back: being a good leader means doing great hires. And doing great hires implies a good amount of empathy. But empathy, sometimes, is a huge obstacle.
When you launch your startup, you’ll have few co-workers, you probably interviewed them yourself, and they most likely come from a close circle of friends, or friends of friends.
If you did your hiring job right, not only they are great professionals, but people you like to share the office with.
Unfortunately sometimes you need to take hard decisions, like firing someone.
Other times your pathetic revenue makes you think it’s not going to be OK, and you start thinking about the great people you involved, and wish you hired people you don’t like.

Guys, I must admit I don’t have a good solution to this. It’s tough, and I fight this thought every now and then.
A good advice that kinda works for me is clarity. These people did a bet on you and your project already, they were aware it was a risky business by definition, there’s no reason to keep them away from the kitchen.
You certainly shouldn’t rush to them and vomit out all your anxiety. I’m suggesting you take scheduled time to let your staff know how things are going in reality, being open to questions and make them feel like what they perceive is what’s really happening. If you let them guess, they may guess wrong, and then when reality strikes them it’s drama.



I’m not trying to discourage you even if it may sound like it. What I’d like you to learn from this reading is: you got to be strong, or at least believe you can become strong.
Don’t let TechCrunch (as an example) fool you, behind any great success there’s sacrifice, even in the glittering startup world.

Sloppy code mayhem

Today I got a bug reported. Shit happens, bugs as well.
I get very nervous when a bug impacts the user in an evident way, so I start working on it immediately. And then, there it is, covered in mist, the Pandora’s box.

We can summarize bugs in three major categories, by the way they impact morale.

a) the WTF bugs. The ones that “Oh my God WHY I haven’t noticed”, but they end up in an easy fix.
b) the OH SHIT bugs. The ones that have a relevant, long-term effect, and you have literally no idea on how to fix them, at least as long as you’re in your panic time.
c) the OMG I’m FALLING INTO A BLACK HOLE bugs. These are an obvious consequence of sloppy work, they live in sloppy code, feed themselves with sloppy data, in a sloppy flow.

Here it is, case C, right in front of my eyes, the day before the deployment of a relevant release no one really wants to deploy.

You have no choice but fixing it, but as soon as you touch it, you start a terrifying journey into a stupid, stupid world, where nothing makes sense, and everything has been built specifically to “kinda work”. It’s a film set for a western movie, where the whole town is made of cardboard and there’s literally nothing behind the front-of-houses.

To fix this kind of a mess, you need to burn down whatever that piece of crap touched and build it right. And it’s horrible.

But who the hell wrote this stuff in first place? Well, you.
See, coding is self-discipline in the first place, and as most things with “self” in it, it’s easily disturbed and implies a lot of things that can mess it up. Like self-esteem. And most selfies.
Hurry is your enemy. If, in a hurry, you code something faster than you thought you could, beware.

Of course, there will be people in suits pulling your leg to have you deliver that super feature in time, if not earlier.
Sure, there will be customers nervously replying “It’s not what I intended, give me what I want now”.
Accepting there’s a minimum standard in quality you can’t go below is the first step. Applying it every time is a journey where you may still fail this rule here and there, but at least you’ll be safe most of the time.

But a “do it right or don’t do it” when it makes sense, is worth your sanity. It’s an investment.
Work toward lowering the expectations on your speed while still providing accurate estimates, and raise the expectations on the quality you introduce. Sure, quality is harder to sell, people won’t grasp it immediately, but this is an investment as well. Being the most reliable coder in the hood is something that will pay off.

For what concerns me, this is going to be a hell of a day…

Apache HTTP Client – Client side SSL certificate

Hello! I’m sharing this snippet with you because it’s been a little tricky to make it work, so I hope to save you some time.
Note: I’m referring to Apache HTTP Client 4.3. You know its API is pretty “lively” so before you dive into this, make sure it applies to the version you’re using as well.


Creating an HTTP connection using Apache HTTP Client is pretty straight forward, and this is why we love it. Fine tuning how the client works is essential in production environments, and it does require a little bit of tweaking, but the results are excellent.

It’s not a surprise that Client side SSL certificates (also known as 2-way SSL or mutual SSL authentication) is doable, but of course, being something that interferes with the intimate nature of the HTTP conversation, the process isn’t exactly straight forward.

If you’re unaware of this security practice, here’s the shortest possible summary:
to provide stricter security for HTTPS connections involving very selected parties, you can let them have a SSL client certificate that will identify them. The SSL dance will not work if server and client certificates are not a match. By doing so, no credential is sent over the Internet, just encrypted data that will be decrypted correctly only if the certificates match.
If you want to know more, here’s a useful article by Robin Howlett.


Certificates are pain already. Incomplete chains, root certificates to be updated etc. So you can assume this couldn’t be a piece of cake right?

First off, let’s be clear about the fact that you are not going to configure this for a specific connection. The Http Client instance will be built around the fact that it will support that certificate.

First, let’s create a keystore:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

The factory will create a JKS keystore by default. You can alter which one you will get by changing the parameter. For example PKCS12 is an option. I’m sticking with JKS for this example. This implies you already created a keystore and added the certificate to it.

Second thing, we load the keystore:


Any inputStream will do. We need to provide a password to decode the keystore of course.

SSLContext sslContext = SSLContexts.custom()
                          .loadKeyMaterial(ks, "password".toCharArray())
                          .loadTrustMaterial(null, new TrustSelfSignedStrategy())

We basically create a custom SSL Context, load the keystore, load the trust store (the null parameter will default to the cacerts file).

SSLConnectionSocketFactory sslConnectionFactory =
                                new SSLConnectionSocketFactory(sslContext,

We create a socket connection factory providing the SSL context. The hostname verifier is literally up to you, and it pretty much depends on the service you will be interactive with. The ALLOW_ALL_HOSTNAME_VERIFIER is loose, so you might want to consider moving it to “strict” if the server allows you to.

Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslConnectionFactory)
				.register("http", new PlainConnectionSocketFactory())

This registry associates what socket factory to use based on the protocol.

BasicHttpClientConnectionManager connManager = BasicHttpClientConnectionManager(registry);

We instantiate a connection manager that will use the registry. We’re using the basic connection manager here because it’s simpler for the example. Connection managers are a vital part of tuning HTTP client, so make sure you’re using something that suits your use case.

HttpClient client = HttpClients.custom()

We finally instantiate our Http client that will eventually be successful when talking to our highly secure peer. Same thing we previously said, the hostname verifier has to be edited based on your needs.
Note: this example contains only the strictly necessary commands to make it work. A lot of other configurations options may be needed in your context.

And we should be set to go.

Let me repeat it, before you dive into this practice, make sure it suits your HTTP Client version. Various refactoring and changes in the API may strongly impact the way to do it.

Hope this helps! Take care.

Lonely as ASDF

I’ve hinted this concept a few times in the past.
Being a software engineer can be extremely lonely sometimes.

This time I’m not trying to be funny, I’m willing to share something important that may be helpful to you to mitigate this feeling.

There are quite common scenarios.

The most typical and less severe one is when you get an assignment you still cannot fully grasp. You already asked clarifications a few times, your source of information is now irritated because of it, and you are jumping from an obscure item to another. You feel stupid and lost.

Good news is this is often temporary!
There’s a bunch of good reasons why you’re not grasping it, and some of them might be easily solvable. For example, I’m totally not receptive when I surpass a certain level of stress. Next day? Totally get it.
Another problem is developers’ urge to receive highly detailed information. We strive to understand most people don’t think exactly like us. Relax, you haven’t written a single line of code, there’s time for details, grasp the concept for now.
But the thing that works extremely well for me is letting the information sediment. You’re now overwhelmed by new data, but dinner out and a good sleep will bring order to that chaos.

The second one is scarier.
It happens when you’re the man in charge of taking certain decisions, you’re asked to take a bold one, and you think you have no one to confront with.
You know how your decision will impact the company, but most of all the work of your mates. You can’t forget how you will be held responsible for it, and if there may or may not be a remedial action.
This situation is common to all people in command, but in software it seems even worse because people will build stuff that will need to work for years on top of your decisions.

The good news is you are in charge. It’s way worse when someone takes shitty decisions for you. Of course being “The Man” comes with a price, but no one will yell “not guilty!” pointing at you when you’re not in charge, yet followed wrong directions from the man in charge.
Also, sometimes you may be lead to think that’s super important you to decide super quickly. If you don’t feel sure, ignore everything and take your time to collect more info. Information collection is one of the most fundamental skills when you’re in command.
Finally, you’re not so alone. Of course you’ve the last word, however you are probably surrounded by geeks. If you built a healthy relationship with them, they will volunteer to help you out. And by doing so, you might discover talents you overlooked.

The third one is shattering.
You just realized you’ve done something horribly wrong and that’s impacting customers and users right now, but the problem is so intricate you have no idea on how to fix it and certainly no one but you is supposed to know. That’s complete desolation. Heart rate sky rocketing, tunnel vision, shaking hands. You will rarely feel so lonely in your whole life; the problem is so scary and you’re so freaked out your mates stay away from you or even flee.

The good news is unless you’re in medical, military or aviation, no lives will be lost because of your fault. If no one dies, everything is going to be fine.
Panicking will not solve the problem, it’ll just make it tougher, and since the issue is already rampaging, spending 5 minutes or 30 minutes to solve it won’t be that huge of a difference.
And even if everybody seems to be fleeing, no one will refuse to help you out if you explicitly ask for it. Often times just explaining the problem to a human being brings you closer to the solution.

The last one is a real problem.
You get to the office, sit in front of your computer and you feel as lonely as you can feel. Nothing makes sense. The work, the office, the keyboard, the colleagues. Literally nothing has a meaning to you. The reasons may vary and may come from inside or outside the workplace, but if you recognize it’s the workplace to cause you such distress, then it’s time to leave and never come back.
We are social animals for a good reason: we are more than the sum of the parts.
Feeling lonely because at times you don’t think you can rely on your pals is one thing, but feeling segregated and helpless is a whole different story.
Regressing to what broke the idyll can be important to avoid it to happen again, but my most sincere advice is: leave.
This kind of toxic situation can lead you to depression and that’s a passage you want to avoid at all costs.
Don’t ask yourself what’s going to happen next if you leave, because I can tell you what will happen next if you don’t: decay.
Remember that if you’re in such situation you’re one step away from an actual mental illness and ANY forecast on your future will look dark, so just accept as a dogma the fact that ANYTHING is better than what awaits you if you stay.

So you might have noticed that the three key things in all these scenarios are: time, communication and desperation.

Time. This is not a hymn to laziness or procrastination, all I want to say is something you might not realize:

We do a job that pushes our brain to work FASTER

Coding is solving complex problems by formalizing all the concepts and wiring them together. It becomes easier and easier when you do it for long time, and your ability to always have control on your overall view becomes stronger. As it grows stronger, you push faster without even knowing it.
When you’re in danger, your adrenaline pumps, it’s our ancestral biology. You become more reactive but less clear headed. You perception of time compresses, you’re moving as fast as light, and everything else is still.
In such conditions, you would be able to run from a lion hunting you, but definitely not solve a jigsaw.
Advice: accept this fact and learn to control it, at least in part. Action sports may help a lot in the process.
Understand that the unknown is not one of your daily challenges, it requires time. If you look at the problem solving approaches of people in other roles, like a project manager or a sales engineer, they don’t try to speed as much as you do. Not because they don’t care, but they tackle it in another way.
Welcome the idea that too little information or too much are equally inadequate to commence your task. You first have to integrate or skim.

Communication. Of course not being supported is a problem, but sometimes you are the one not communicating at all. Frantically yelling at your screen is not communicating and scares people. Moreover, when you’re drowning in shit and the world is in time lapse, they all look like lazy asses doing nothing and not caring at all. Trust me, it is you. You can’t expect them to be emotionally dragged into your madness, and if they did, they would become completely useless.
Be humble and generous when things are OK, and people will try to help you when things are KO, whether you want their help or not.

Desperation. When you’re desperate no decision is good. But between a desperation cycle and another, there’s a time you feel less miserable, therefore you’re more clear headed. If you’re really down, postpone any critical decision that can be postponed to a better time, but don’t forget about them. When you feel you can handle them lucidly, do so, be logical, brave and definitive.
You should never let the desperation be an inevitable part of your week, because the lucid times will get shorter and shorter down to depression.

Finally, listen to this advice very carefully, it’s the most important one.

Never let a workplace that makes you feel lonely poison you to the point you hate what you used to love most.

How (not) to tell your mom how you earn your living

Your mom won’t feel fulfilled until you tell her you’re a “manager”.
The word “manager” has a clear etymology: (person) that manages (persons/things), but
for every non English country that actively uses the English word “manager”, that word means: wealthy, money-handling rampant white collar.

But you don’t want to be a manager, you want to be a software engineer, a web developer, a data analyst.

“Mom, I am software engineer” you timidly come out.
“So what do you do exactly?” she asks, emphasizing the word “exactly”.
BEWARE, she’s not really interested in what you do, but since you’re not a manager, she wants to make sure you’re doing fine, and one of the ways to discover that is understanding what you do to earn your living, in detail.

This is the origin of some of the most hilarious and annoying anectodes I’ve ever heard. And yes, some of them are Italian moms. If your parents are now 65+, this has certainly happened to you too as well.

Here’s some of the best. these are ALL REAL:

You: I do websites for mobile devices
Mom: Like websites for the computer?
You: Yeah, for mobile devices
Mom: How is that even possible… oh you mean texts!

You: We build a social network
Mom: Facebook?
You: No, not Facebook. It’s…
Mom: Is it like Facebook?
You: No…
Mom: But you said it’s a social network

You: I work at a startup
Mom: Oh God, that’s a problem, right?

You: It’s a tool that helps people sharing their cooking recipes
Mom: Good lord, you could ask your mom
You: Mom, it’s not for me it’s for other people
Mom: You can’t even pour your cereals and you give advices to others?

You: I’m a software engineer
Mom: Basically computers, right?
You: Yes
Mom: Good, the boy that fixes my laptop from viruses is very pricey

You: Yeah, in my work I need to use the Internet a lot
Mom: Be careful

You: I’m a freelance web developer
Mom: So you have to find your own customers
You: Yes
Mom: But how do you do that? You have to be skilled to do that

You: Yes mom, it’s an intensively intellectual work
Mom: All that thinking must be very stressful. I wonder why you never looked into that postal office job offer I told you about

And I could go on and on.

At the end of the day, even if some of them are tragically annoying, they are all driven by love. Don’t get mad at your mom, hug her (and maybe she will stop talking for a minute or two).