Friday, November 11, 2016

Amazon SQS with Spring java framework and maven


In this post i'll try to guide you through 5 easy steps to connect your java application to Amazon SQS ( Simple Queue Service). For this purpose i'll use Spring framework and maven for dependencies management.

 What is AWS SQS ?


The simplest answer for this question is directly quoted from AWS :

"Amazon SQS is a distributed queue system that enables web service applications to quickly and reliably queue messages that one component in the application generates to be consumed by another component. A queue is a temporary repository for messages that are awaiting processing."


Why to use queues at the first place ?


In web applications API calls might not be the answer for every case. Lets look at the following case :

Imagine we have 2 web services ( Cart, EventsRepo) and we want to keep track for all events resulting from customer cart  ( ex : add item to cart, delete item, replace item .. etc ) . So for each request coming to the ( Cart service ) we want to create the responding event and send it to ( EventsRepo ) service for further processing.

Now imagine we have 30 other services that want to send events to our EventsRepo. Then we should be able to handle a s*** load of requests coming to the  EventsRepo  service and that means of course spawning more instances and paying more money.

In this case a messaging communication would come really handy, where all service put there events in a queue and our EventsRepo will consume the events one by one . With this approach even one instance of EventsRepo would be enough ( more instances means faster processing for events in the queue ).


What makes SQS so special ?


When it comes to queueing systems there is a lot of options out there ( rabbitMq,  Redis,  Kafka .. etc) and each with its own pros and cons, so before jumping to SQS i'd suggest more in depth reading about other tools to find out the best choice for your use case.

Thats said,  i've found SQS so simple and easy to use . There is no prior setup or maintenance overhead needed,  just AWS credentials and you are ready to go. So if you are looking for something simple with basic queuing functionalities then SQS is your friend.

How does it work ?


In SQS every thing is a request and you'll be billed on request base, we have 3 basic types of requests ( send message - receive message - delete message ).

For one message it'll take 3 requests in normal case to handle it :

Sender  => 1 request to send the message .

Receiver => 1 request to receive the message and 1 request to delete it from the queue.

So keep in mind normally each message needs 3 requests and ( 1 mil requests cost 0.5$ ) .


Note1 : SQS follows (producer/consumer) model not (publish/subscribe) model.
i.e : only one consumer will receive the message at the same time.

Note2 : There is also batching possibilities for sending and 
receiving but it is out of this article scope.

  •  Step (1) - Create the queue :




As you can see creating the queue is straight forward,  lets go quickly through the important properties :

- Default visibility timeout :  how long should SQS wait before making the message available again for other consumers. If we have 2 consumers reading from the queue ( consumer1, consumer2 ), and if consumer1 read a message but did't send the acknowledgment back ( i.e : delete request ), then the message won't available for consumer2 until default visibility timeout is over.

- Message Retention : how long the message should stays in the queue if its not consumed.

- Receive Message Wait Time : this is important to reduce SQS costs and it means how much time
the receive call should wait before returning empty result to consumer.
i.e : lets say the queue was empty for 2 minutes then during this time all  receive calls made by consumers are useless, so long polling receive call will guarantee a reasonable waiting time before returning empty result and forcing the consumer to make a new call .

  • Step (2) - Add maven dependencies :

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-aws-context</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-aws-messaging</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-aws-autoconfigure</artifactId> </dependency>

for more information about these dependencies visit  Spring cloud

  • Step (3) - Create the beans:


As you can see here i'm using the ( DefaultAWSCredentialsProviderChain ) class which will scan my environment for valid AWS credentials, but feel free to use another provider.  For more info about this topic AWS Credentials .

  •  Step (4) - Send the message :


Sending message is that simple, we just pass the queue name and the object we want to send to SQS ( it'd be converted to JSON by default).

  •  Step (5) - Consume the message:
 Also consuming is a piece of cake !  We just need to add (@SqsListener) annotation before any function and it'd become our consumer. You can notice here we set our deletion policy to ( ON_SUCCESS ) and that means we will only send the delete request to SQS when the consuming is completed successfully.


Thats it ! now you can start using AWS SQS, of course there is more details and we just scratched the surface in this article, but this is the basic and simplest steps to start production using SQS.

Note 1: To write integration tests for SQS we can use elasticMq it might be little tricky to configure it especially with spring auto configuration around, but i've used it and its working nicely .

Note 2: After sending and receiving couple of millions of messages the problem described in the following issue might occur, till the issue is fixed you can use the (@Aspect) solution described in the issue comments.



Wednesday, November 9, 2016

A Look back


March - 2011


The Syrian revolution against Assad's regime started.  Looking back to that time and knowing the nature of the dictatorship Syria was suffering from, i can only say it was a miracle !

 Assad's family and relatives were like Gods in Syria, president pictures were everywhere ( schools, hospitals, shops, in the streets and even in houses ), no one can ever criticise or talk about them.

 I even know someone imprisoned for 8 years just because of laughing at a joke about the president ( you can imagine what happened to the one who told the joke ). Having all of that in mind i still can't believe how people were able to protest in the streets against the regime. But i guess after all, Bob Marley was right when he said :

  "Better to die fighting for freedom then be a prisoner all the days of your life."

I still remember my first demonstration, every little detail: heart beats, fear, heavy breath, sweating, hope and Freedom! I felt like a free man for the first time in my life and it was literally like being reborn again.

Assad's family ruled Syria for the past 40 years



November - 2012


I graduated from Damascus university with a very good GPA and met a girl who would become my wife in a couple of years.

 It was the second year of the revolution, most cities and areas continued with the peaceful demonstrations despite the brutality of the regime ( on average  500 - 600 people were getting killed every month either by police's fire in demonstrations or under torture in regime's prisons ), nevertheless in some parts of the country the revolution started to be an armed one.

The armed forces in those areas were basically some people decided to protect themselves  or soldiers who disobeyed the commanders orders to shoot at people and decided to defend them instead .


Syrian protests by singing and dancing

September - 2013


By that time things in Syria were a complete chaos, the regime used all different types of weapons to regain the control over rebels areas ( barrel bombs , chemical weapons, aircrafts, tanks ... etc).

Besides that islamic extremist groups were rising and crazy people were literally pouring from all around the world to fight either with the regime or with the rebels, it was like a third world war taking place in my Country!

 Whole cities were vanishing because of heavy bombing from the regime, the rebels also started to use Mortars to shell areas held by regime and the true victims were the civilians trapped at both sides.

 As i was living in Damascus i didn't suffer as much as other Syrians in cities like Homs  or Aleppo, but nevertheless Damascus witnessed a lot of explosions, mortars, shootings and even Israel hit Damascus suburbs few times, .

After living in such circumstances for a while you stop caring about your own safety, but the real pain is you can't stop caring about the ones you love.

After every explosion you can just pray no one you know got harmed, the seconds elapsing till they pick up their phones are nothing but hell on earth.

Syria - Homs

October - 2014


By this year i had already lost more than 6 friends (killed by Regime snipers, bombed or tortured to death in regime prisons). Hundreds of militias fighting each other in my country, destructed cities, hundreds of thousands killed and millions became refugees.

Economy was ( and still ) falling apart, the currency lost about 400% of its value,  we had electricity only for ( 2 - 4 ) hours a day, apparently there was no way to live a descent life in Syria anymore so i started looking for jobs abroad and after 4 months of tests and really long process i was accepted at ( Mindvalley - Malaysia ).

By the end of October i got married and traveled with my wife for the first time in my life to live and work in a country on the other side of the planet !

Something i'd never forget is my last day in Syria. Saying goodbye to your family knowing that you might never see them again, the last looks at your home town which might become a pile of rocks during this crazy war. And the worst is burying your dream of freedom and dignity for your people and country.

Refugees leaving their destructed houses near Damascus


August - 2015


Moving to Malaysia and working at Mindvalley was a life changing experience, i met people from all around the world and interacted with different cultures and religions for the first time in my life which  opened my eyes and mind to a new world where i never judge a human being by his look or believes. 

After one month in Malaysia my wife got a job in Germany, considering our situation as Syrians she couldn't refuse the chance, so she traveled to Berlin and we hoped i'd follow here in a couple of months . So basically we were separated after only one month of our marriage.

In the second week of August i received the reunion visa from the German embassy and the job offer from Zalando ! Although It took me one year to get a visa to Germany, but it was amazing, challenging and educating experience.

Maylasia - Cameron Highlands


November - 2016


Working in Germany for a company like Zalando is really awesome. I learned a lot and grew a lot both professionally and personally this year.

During this year i've also traveled to ( Slovakia, Poland, Czech republic, Italy, Greece ) and every journey was an eye opening experience for me because as Saint Augustine says  

"The world is a book, and those who do not travel read only a page."

Slovakia - Tatry


So to wrap it up, In 6 years :

 i  joined a revolution , fall in love, witnessed a war, lost friends, got married, worked abroad, visited 7 countries and met tons of new people and cultures.