Category Archive » Uncategorized

HowToGuide: Redirecting Rails Read Queries to Slave using Makara Gem and Postgres Streaming Replication.


Postgres is a popular database management system, There are many way to set up replication on a postgres system. Here I will cover How to configure replication using a hot standby, and then with the help of makara gem Redirecting Rails Read Queries to Slave server.

For this We need two ubuntu 14.04 VSP servers. Out of which one will be our master server and other will be slave server.

Install Postgres Server:

Following steps need to be performed on both the servers.

For installation of postgres run the following commands.

 sudo apt-get update
 sudo apt-get install postgresql postgresql-contrib postgresql-client

By Default PostgresSQL creates a user called “postgres” in order to handle its initial databases. We will need to set a password for the postgres user so that we can transfer the key files initially.

 sudo passwd postgres

Switch over to the postgres user:

 sudo su - postgres

Generate an ssh key for the postgres user:


Press “ENTER” to all of the prompts that follow.

Transfer the keys to the other server by typing:

 ssh-copy-id IP_address_of_opposite_server

You should now be able to ssh freely between your two servers as the postgres user.

Configure the Master Server:

All of this commanded should be executed with the postgres user.


Create user called “rep” that can be used solely for replication:

Next, we will move to the postgres configuration directory:

 cd /etc/postgresql/9.3/main

We will modify the access file with the user we just created:

 nano pg_hba.conf

At any place not at the bottom of the file, add a line to let the new user get access to this server:

 host replication rep IP_address_of_slave/32 md5

Save and close the file.

Then open postgres configuration file:

 nano postgresql.conf

Find these parameters. Uncomment them if they are commented, and modify the values according to what we have listed below:

 listen_addresses = 'localhost,IP_address_of_THIS_host'
 wal_level = 'hot_standby'
 archive_mode = on
 archive_command = 'cd .'
 max_wal_senders = 1
 hot_standby = on

Save and close the file.

Restart the master server to implement your changes:

 service postgresql restart

Configure the Slave Server

Firstly you need to shut down the slave server

 service postgresql stop

We will be making some similar configuration changes to postgres files, so change to the configuration directory:

 cd /etc/postgresql/9.3/main

Allow the other server to connect to this. This is in case we need to turn the slave into the master later on down the road.

 nano pg_hba.conf

Again, add this line somewhere not at the end of the file:

 host replication rep IP_address_of_master/32 md5

Next, open the postgres configuration file:

 nano postgresql.conf

You can use the same configuration options you set for the master server, modifying only the IP address to reflect the slave server’s address:

 listen_addresses = 'localhost,IP_address_of_THIS_host'
 wal_level = 'hot_standby'
 archive_mode = on
 archive_command = 'cd .'
 max_wal_senders = 1
 hot_standby = on
 Save and close the file.

Replicating the database:

Before we start slave replicate the master we need to give initial database to build. This is because it reads the log of master server and applies the changes to its own database. we need database to match the master database.

On the master server, we can use an internal postgres backup start command to create a backup label command. We then will transfer the database data to our slave and then issue an internal backup stop command to clean up:

 psql -c "select pg_start_backup('initial_backup');"
 rsync -cva --inplace --exclude=*pg_xlog* /var/lib/postgresql/9.3/main/ slave_IP_address:/var/lib/postgresql/9.3/main/
 psql -c "select pg_stop_backup();"

Now we have to configure a recovery file on our slave server. on slave navigate to data directory.

 cd /var/lib/postgresql/9.3/main

Here, we need to create a recovery file called recovery.conf:

 nano recovery.conf

fill the following information.

 standby_mode = 'on'
 primary_conninfo = 'host=master_IP_address port=5432 user=rep password=yourpassword'
 trigger_file = '/tmp/postgresql.trigger.5432'

Make sure to change IP address and password for rep user.

The last line in the file, trigger_file, is one of the most interesting parts of the entire configuration. If you create a file at that location on your slave machine, your slave will reconfigure itself to act as a master.

This will break your current replication, especially if the master server is still running, but is what you would need to do if your master server goes down. This will allow the slave to begin accepting writes. You can then fix the master server and turn that into the slave.

You should now have the pieces in place to start your slave server. Type:

service postgresql start
You’ll want to check the logs to see if there are any problems. They are located on both machines here:

 less /var/log/postgresql/postgresql-9.3-main.log

You should see that it is successfully connecting to the master server.

Use makara gem

Makara is generic master/slave proxy. It handles the heavy lifting of managing, choosing, blacklisting, and cycling through connections. It comes with an ActiveRecord database adapter implementation.


 gem 'makara', github: 'taskrabbit/makara', tag: 'v0.3.x'


 adapter: 'mysql2_makara'
 database: 'MyAppProduction'
 # any other standard AR configurations# add a makara subconfig

   # the following are default values
   blacklist_duration: 5
   master_ttl: 5
   sticky: true

   # list your connections with the override values (they're merged into the top-level config)
   # be sure to provide the role if master, role is assumed to be a slave if not provided
     - role: master
     - role: slave
     - role: slave

Pictionary is More Fun with Bad Drawings and Weird Guesses

Have you ever played Pictionary?

If yes, you must not have played it the way we did.


Recently, at Parity Cube, our employees were engaged in a fun filled Friday playing pictionary.

Unlike the actual rules of the game, our HR and hosts- Geeta and Ekta gave it a little twist. 5 teams with 7 talents in each were formed. Each team was given a minute to guess the drawing.

A team player was supposed to pick a dice from a box. Then they were supposed to pick a card. Whichever colour dice they had picked, they had to draw the object mentioned in that colour on the card.


Every player was allowed only once to be the picturist (the player who draws for the team).

Well obviously we allowed the other teams to distract the guessers.

Do you want to know some of our hit guesses & drawings?


Akshay had drawn a long triangle trying to explain his team a famous monument. His team ended up guessing it to be mountain, tower, Alphabet “ A ” etc. whereas it was an Eiffel Tower.

Anil drew an airplane and some chaat hawkers trying to explain fast-food, but his team guessed it as fast, food, airplane, garden, pani puri, bhel, etc.

Another team player drew rain to explain monsoon, his team ended up guessing rains, water, rainbow, sweater, umbrella and everything else.

Dhrumi was trying to explain direction to her team with the help of an arrow and a hand… but her team could only guess that it was a hand, an arrow but not the actual word “ right”.



The winning team was Sumit’s team. Their team could guess the maximum number of drawings. They scored the best and the highest amongst all the teams.

Desidime Turned 5 this July

Birthdays are always special, no matter how many years pass by, but this year was a tad bit extra special for us because it is with this birthday that we entered a new phase of growth. To quote the founders, this year “we enter a phase in our journey where we turn a new page… from doubts to clarity from uncomfortable situations to even more uncomfortable situations… To learn things we have not learned so far… “

Thus, no doubt, a grand celebration was in order, and like eager teenagers we decided to have a dress-code for the party.

Thus, there we were all, wearing our hard-work on our backs, for that is what the DesiDime t-shirts represent to us- hard work and passion.


We also decided to surprise our colleagues a little, and so we had the office all decked up with balloons, before they punched-in for the day. (BTW, ‘punch in’ is just a phrase here; we don’t really believe in having a machine that makes you feel guilty about every single minute you could not be in office.)


And these red and white festoons are still up for the employees to indulge in some post-work fun bursting-spree. It also doubles up as a stress“buster”, you know… when a colleague gets too irritating, take it out on these balloons while they last.

Another small surprise for our staff was a small gesture in form a ‘Thank You’ note sitting on their desk when they arrived in office. It is our workforce that has helped us reach this milestone; this was the least we could do to show our gratitude to them.


Even though everyone in office is well past their schooling days, we had no qualms in ordering a massive cake in the shape of the number 5 (in case, someone forgot which birthday it was ;) )


The birthday celebration coincided with the joining of a new member, Gustavo to the PCPL family. So, it was this jolly good fellow from Brazil who was asked to cut the sinfully yummy Red Velvet cake on behalf of the company. The guy was all blushes and manners… stood with his slice in hand till everyone got theirs. Bless him!


After everyone managed to grab as much of the cake as they could, they were served with some smoking hot missal and cold drinks.

These days you just can’t have a birthday party and not click a selfie! After all it was our 5th birthday! So, we all squeezed in together and the pogonophile* boss somehow managed to capture 35 of us in a single frame. (*Yeah, he has a thing for beards)


This was followed by some inspiring words from the bosses.


Just before the close of the party, it was time for the announcement of the ‘Employee of the Quarter’. Our Office Help cum Administrative Assistant, Datta was the proud and deserving man who got to hold the shining cup, this time. It was in recognition of his efforts, as he not only made tea, coffee and took care of all the sundry things that keep the office going but also helped the HR and Admin team with all the filing and assembling.


A befitting end to a perfect evening.

10 Reasons Why You would Love to Work with Us

Greetings our new or potential teammate-to-be! Maybe you’ve just received an LOI from us or maybe you simply stumbled upon us while looking for a job. Either ways, you are here to know a little more about what kind of a place and people we are, and whether you will like us or not. We know the apprehension surrounding the decision of taking up a new job, so to allay your immediate fears, let us tell you, we are a fairly relaxed bunch, who value talent above anything else in people.

Furthermore, here are a few more things about us that we would like you to know.

We don’t judge the book by its cover

As long as you know what is acceptable at a workplace, you can walk in to the office wearing your most comfy outfits and get down to working, without much pretense.


The first name culture

We love being addressed by our beautiful, meaningful first names, so do you, we hope. Words like ‘Sir’ and ‘Ma’am’ are banned here.

first name

Get to drive your own ‘car’eer

Nobody knows your real potential better than you. That is why, you get to set your own quarterly goals here, define your own daily tasks and be your own worst critic.


There is a genie waiting for you here

Our monthly Lucky Draw Scheme gives you a once-in-a-tenure opportunity to demand anything from the bosses that will inspire you to work harder. So, start deciding on what you desire the most. So far, people have grabbed a MacBook, a laptop and some online courses.


Get to try on some new hats

Of course you will have a proper job title and a defined work profile, but when the situation arises, we are sure you would be glad to widen your horizons and learn new things.


The Rooster Award

Naturally, you can’t escape our notice if you manage to do more than what is expected of you. Every quarter, our most hard-working employee gets a shining cup and a gold coin as a recognition for his/ her efforts.


The parties are always harder

We sure don’t want to end up with dull Jack’s and Jill’s in our office. So, we try to balance all that hard work with as much play in form of monthly Birthday celebrations, fun games and HR events, at times even, putting up projectors for World cup matches.


The creative space

When cubicles, desks and people start getting awfully formal and restrictive to your thought process, you can escape in to the ‘Bean Bag Room’ for some uninhibited introspection, exploration, or even personal growth during the self-learning hours on Fridays.


Holiday with colleagues

Just like the work culture, our yearly picnics and getaways are never the routine, done-to-death water parks or resorts… they’re more on the lines of trekking, rafting, camping, barbecues etc.


Never go hungry

We understand the deep connection between food and motivation for work, so we keep our fridge and snack-boxes stocked with munchies to sate your hunger before it gets to your head.


Last but not the least, be the first to know and grab all the best deals in town and save a lot of your hard-earned money.

Hope, we’ll see you around soon!

The Whereabouts of Parity Cube

Traveling can be one of the most frustrating part of a new job, especially in a city like Mumbai. You are already dealing with the anxieties of being among new people, adjusting with the new culture, settling in to a new work routine and add to it the commuting woes, which can well be the last straw for your already strained nerves. Also, if you are from out of Mumbai, you have food, bed and board to think about, too.

So, to make your journey to PCPL a little smoother, we have put together this piece on how best to reach us along with some help on settling in this city, if you are new, here.


To begin with, here’s where we are located in Kandivali East.

map2 copy1

How to reach

No matter where you stay in Mumbai, the PCPL office is pretty convenient and affordable to reach because we are opportunely positioned right beside the highway as well as at a walk-able distance from the nearest railway station.

If you stay far, you can use Mumbai’s lifeline- the local train to reach Kandivali station on Western line and then opt to walk or take a ‘sharing’ rickshaw to reach the office from the station. The rickshaw fare is just Rs 7 to Rs 10 per head. If you are new to Mumbai, we recommend you download the m-Indicator app on your phone to work out all the train routes, timings and ticket fare. Those who stay in the heart of suburbs can choose to travel by bus, cab or auto as per their convenience. The nearest bus stop, Bandongri is right across the street from the office.

If you are among the lucky ones like our colleague Evgeny, who rents a place in a nearby residential building, you will be skipping in and out of office every day.

Around the workplace

As our postal address suggests, we are right beside one of Mumbai’s most beautiful malls, Growel’s 101. So, you will just have to hop to your right for some binge eating or window shopping, or catching up on movies, right after work or picking up some groceries and home essentials while going home. If you like playing snooker or other such games during your breaks, the game zone is not far away.

Also, if you love your junk food, you’ll get it right outside the office building, along with a chance for animal lovers to pet some of the stray dogs the commercial complex has adopted.

House hunt

Not from Mumbai? Here are some brokers’ contact numbers that we have curated from our other colleagues who have been through this routine before.

Indira – 09769460888

Arijit – 08976340641

Raj – 09004646555

Vishal – 09820806926

Ritesh – 08983317122

Kunal – 9967042431

… and here some numbers for the nearby Andheri-East area as well.

Sandeep – 9821812050

Ramesh – 02230160552

Vikas – 02230141883

If you are a total stranger to this city and its ways, you can also take guidance from anyone in the PCPL family.

Hope this will make the beginning of your journey at PCPL much easier.

VIM Editor – Basic Commands

VIM Editor – Basic Commands

Vim editor is a versatile and extremely powerful tool for manipulating plain text, managing system configuration files, and programming. Vim has insertion and command mode, it begins with command mode, where the cursor movement and text deletion and pasting occur. Insertion mode begins upon entering an insertion or change command. [ESC] returns the editor to command mode. Most of the commands are executed instantly, except for “colon” commands which execute when you press the return key[Enter].

Here are few basic VIM commands

Cursor Movement Commands

h   Move left
j   Move down
k   Move up
l   Move right
w   Move to next word
W   Move to next blank delimited word
b   Move to the beginning of the word
B   Move to the beginning of blank delimted word
e   Move to the end of the word
E   Move to the end of Blank delimited word
(   Move a sentence back
)   Move a sentence forward
{   Move a paragraph back
}   Move a paragraph forward
0   Move to the begining of the line
$   Move to the end of the line
1G  Move to the first line of the file
G   Move to the last line of the file
nG  Move to nth line of the file
:n  Move to nth line of the file
fe  Move forward to e
Fe  Move back to e
H   Move to top of screen
M   Move to middle of screen
L   Move to botton of screen

Insertion commands

i Insert before cursor
I Insert before line
a Append after cursor
A Append after line
o Open a new line after current line
O Open a new line before current line
r Replace one character
R Replace many characters

Copy(Yank) Commands

yy  Copy the current line
:y  Copy the current line
yw  Copy one word, where the current cursor is placed
nyy Copies n lines starting with current line

Delete Commands

:x  Save and Exit
:q  Exit only when there are no changes, or else alert to save
ZZ  Save changes and Exit
:q! Force Exit without saving the changes

Paste Commands

p Paste after the cursor position or after the line
P Paste before the cursor position or before the line

Undo Commands

u Undo last change
U Undo all changes to line

Window Commands

[Crtl+w+arrow key] To Shift from one window to another
:vsp filename To open file in vertial window
:sp filename  To open file in horizontal window

Substitution Commands

:s/old/new/g to substitute 'new' for 'old' where g is globally

[Rails] ActiveRecord Time Zone – Not Automatically Set in Rails…

I bumped across this very interesting problem related to ActiveRecord time Zone…

I had some code snippet like this:

 query = "INSERT INTO link_logs VALUES(DEFAULT,'#{self.url}','#{self.affiliatized_url}','#{self.publisher_id}',DEFAULT,DEFAULT)"

Basically, a very simply Insert query to push url, affiliate_url , publisher_id and timestamps….

Problem: Timestamps were getting inserted in UTC Time Zone…


First, I checked Application Time Zone in config/application.rb and it was correctly set to Mumbai.

config.time_zone = 'Mumbai'

I then used ActiveRecord to insert records and Voila, it obeys the time zone set in application.rb

However, When done via execute query, It defaults to UTC TimeZone… Here’s what even the console says:

irb(main):001:0> Rails::application.config.time_zone

=> "Mumbai"

irb(main):002:0> Rails::application.config.active_record.default_timezone

=> nil

Turned out,  an open bug already exists for the same:

A workaround appears to be adding the following line to application.rb:

config.active_record.default_timezone = :local

Strongly would suggest from my experience, to avoid surprises, Active Record Default timezone must be manually set for any rails app

[jQuery] How to remove text between two divs

While working on one project, I came to weird problem:

how to get rid of text that is between two div tags and is not captured in any tags?

To be specific, here is what I mean:

<div class="first">Some content</div>
Here is our text we wanna get rid of. 
<div class="second">Some other content</div>

The problem here is, that text is not surrounded by any HTML tag. Then it would be too easy. jQuery can easy hide() or remove() content.

So how do we go about it?

Well, I googled and tried a lot of solutions (eg. trying to put ending p tag before second, and starting p tag after first div) but that didn’t seems to help. So I gave up with trying to enclose text and then remove it. Finally, I came to this code:

jQuery('.first')[0].nextSibling.nodeValue = '';

nextSibling property of DOM and does exactly what you’d expect. So then we can easy set it’s nodeValue to empty string. That’s what we wanted right?

Here is a working example.

But what if there is more of those things?

Yes, that’s exactly what I was facing. My code is more like this, in fact:

<div class="first">Some content</div>
Here is our text we wanna get rid of. 
<div class="second">Some other content</div>
<div class="first">Some content</div>
Here is more text we wanna get rid of. 
<div class="second">Some other content</div>

Here’s where the 0 from jQuery code comes in role. In fact, before we expected to have just one first div. Now we have more divs, so let’s make sure all of them got noticed.

for (i = 0; i < jQuery('.first').length; i++) {
        jQuery('.first')[i].nextSibling.nodeValue = '';

Here is working example.

Is that it?

Well, yes, if the only thing you have between two divs is always only text without any more HTML tags. If you have tags there, you will need to do some extra work.

And yes, you could use remove() on nextSibling as well.