SlideShare a Scribd company logo
1 of 50
Download to read offline


Microservices
with
Zoran Majstorović

github.com/zmajstor

twitter.com/z0maj
Content
• Intro

from monolith decoupling to microservices integration

• The Main Part

microservices messaging with RabbitMQ/AMQP

• Ruby Code Refactoring 

from ActiveRecord Callback to Consumer as a Microservice

• A Simple Microservice Deployment

in docker container to AWS ECS
Let's start with a bad
example
A better example
... or can we just publish the event and let subscribed consumers do the work?
a complete to-do list for this event
Decoupling
Publisher / Producer
Subscriber /
Consumer
Subscriber /
Consumer
Subscriber /
Consumer
Monolith vs Microservices
vs
Complexity in

Interactions
Code

Complexity
Microservice
• a small program that handle one task

• independently deployable

• work together by communicating so that can accomplish
the larger task

• integrated system on the whole provides value
https://martinfowler.com/
articles/microservices.html
https://youtu.be/wgdBVIX9ifA
App Integration Options
• File Transfer
• Shared Database
• Remote Procedure Invocation
• Messaging
While all four approaches solve essentially the same problem,

each style has its distinct advantages and disadvantages.
http://www.enterpriseintegrationpatterns.com/patterns/messaging/IntegrationStylesIntro.html
File Transfer
Consumer A
Consumer B
Consumer C
DATA

FILE
Producer
Export Import
Shared Database
Consumer A
Consumer B
Consumer C
Producer DB
Remote Procedure
Invocation
Consumer A
Consumer B
Consumer C
Producer
Call
Result
Messaging
Exchanges Bindings Queues
Consumer A
Consumer B
Consumer C
Producer
AMQP 0-9-1 Message Broker
• a binary, networking protocol with minimal overhead

• originated in 2003 by John O'Hara at JPMorgan Chase

• version 0.9.1 was specified in 2008

• in 2011 OASIS standards group change it to a
significantly different beast
AMQP 0-9-1
• virtual host is a logical partition within the server 

(a multi-tenant system similar to virtual hosts in Apache/Nginx)

• each of virtual hosts can have many connections,
channels, queues, exchanges and some other things

• bindings binds an exchange to a queue or many queues

• exchange can be: direct, fanout, with topic or headers
• queue is a buffer that holds messages on behalf of a
consumer (or consumers)
The Producer
• external application which creates messages and
decides:

• how the attributes should be configured for routing

• from which exchange the messages should start from

• what is the actual payload that is being sent
The Message
• an atomic unit of processing

• consists of:

• content (body, bare message or payload)

• attributes - metadata about the message like content type,
encoding, routing key, whether the message will be persistent or
not, and whether it has a priority level, etc.

• is created (published) by the producer
• may go through more than one exchange before landing in
the right queue
The Exchange
• Direct exchange route messages based on an exact match with the
specified routing key
• Fanout exchange automatically route the message to all the queues
known to them (ignores the routing key)

• Topic exchange pattern match on the routing key (topic) to route the
messages

• Header exchange use the message header attributes for matching the
queue

• Default (anonymous) exchange is a direct exchange (created
automatically) which routes messages with empty exchange name - it
compares routing key with the queue name
Multiple Queues and
Consumers
Consumer A
Queue 1
Queue 2
Queue 3
Consumer B
Consumer C
The Consumer
• external application which is subscribed to one or more queues

• alerted whenever a message shows up in the subscribed queue

• can poll the queue at regular intervals to see which messages
were added in the queue since the last time it made the request

• can send acknowledgments back to RabbitMQ that the
message has been:

• received (known as ack), or

• rejected (nack for negative acknowledgments)
Bindings
• Routing Key

• Publisher: exchange.publish(payload, routing_key: 'foo')

• Queue Binding: queue.bind(exchange, routing_key: 'foo')
• Headers

• Publisher: exchange.publish(payload, headers: { ... })

• Queue Binding: queue.bind(exchange, arguments: { ... })
• an message broker implemented with Erlang/OTP

• implements all the AMQP 0.9.1 concepts:

messages, queues, exchanges, bindings, virtual hosts ...

• ... and with plugins for other messaging protocols such as

STOMP, XMPP, and more

• has fantastic client support in a variety of popular
languages: Ruby, Python, Java, PHP, C#, JavaScript, Go, Elixir,
Objective-C, Swift, ...
Gems
• Bunny - AMPQ client for Ruby (MRI)

• March Hare - AMPQ client for JRuby

• Sneakers - a background consumer/worker 

• Hutch - asynchronous inter-service communication

• RabbitMQ HTTP API client (various management features)

• Ruby RabbitMQ Clients Blog: http://
blog.rubyrabbitmq.info/
Features
• No message loss 

• Persistent Messages 

• Publisher Confirms 

• Message Acknowledgment 

• Mirrored Queues

• Message Ordering
• Dead Letter Exchanges 

• Alternate Exchanges 

• Message and Queues TTLs 

• Consumer Priorities 

• Federation

... and many more
Back to Refactoring
... or can we just publish the event and let subscribed consumers do the work?
Introducing Publisher
Publish Message with Topic
Message Consumer
Publish Message with
Headers
Message Consumer
Better Ruby Code
https://github.com/jondot/sneakers

https://github.com/gocardless/hutch
Patterns
=
proven solutions
to recurring
problems
www.enterpriseintegrationpatterns.com
Messaging Patterns (65)
Creative Commons Attribution 4.0 license.http://www.enterpriseintegrationpatterns.com/patterns/messaging/index.html
Microservice Messaging
Benefits
• language-agnostic

• amplifies loose-coupling

• makes scaling and rearchitecting simpler

• better reliability and availability - messages will be waiting
until the consumer is ready to process them

• multiple communication patterns: events, message/reply,
notification, async request-response, pub/sub, etc.
Microservice Messaging
Drawbacks
• introducing new complexity into the system 

(the message broker)

• a failure in the message broker can cause severe effects
on the system (highly-available message broker)

• big messages can cause network congestion

• "eventual data consistency" (instead of immediate
consistency across different microservices)
Message Consumer Microservice
Deployment

with Docker

to AWS ECS
Installing Docker CE on
Workstation
• macOS: https://store.docker.com/editions/community/docker-ce-
desktop-mac 

• Linux Ubuntu: https://store.docker.com/editions/community/docker-ce-
server-ubuntu 

• or any other Linux distro: https://store.docker.com/search?
offering=community&operating_system=linux&type=edition
My Ruby Project Structure
Dockerfile
docker-compose.yml
docker-compose build my_consumer:1.0.0
Elastic Container Registry
export repositoryName=my_consumer 

export repositoryURI=123456789012.dkr.ecr.us-east-1.amazonaws.com 

export containerName=my_consumer 

export ver=1.0.0

export imageURI=$repositoryURI/$repositoryName:$ver
aws ecr create-repository --repository-name $repositoryName
eval $(aws ecr get-login --no-include-email)
docker tag $containerName:$ver $imageURI
docker push $imageURI
Elastic Container

Service (ECS)
• logical way to group resources (Tasks and Services)

• currently provides two launch types: 

• EC2

• Fargate (abstract away EC2 instances)

collection of ECS resources: https://github.com/nathanpeck/awesome-ecs 

export clusterName=staging

aws ecs create-cluster --cluster-name $clusterName
ECS Cluster

Building Blocks
Task Definition
• specify the resources for a Docker container or group of containers, such as:

docker image (registry), ports, CPU/RAM, logs, any volumes, environment
variables, etc.

Task
• running containers according to the Task Definition (one-off or long-running)

• TaskRole allow access to S3, DynamoDB, etc.

Service
• manage long-running tasks (defines desired count and replace failed containers)

• integrates with Elastic Load Balancer
ECS Task Definition
{
"containerDefinitions": [
{
"command": [
"bin/worker"
],
"workingDirectory": "/app",
"essential": true,
"image": $imageURI,
"logConfiguration": {
"logDriver": "awslogs"
},
"name": $containerName
}
],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"family": "my-consumer-fargate",
"networkMode": "awsvpc",
"requiresCompatibilities": [
"FARGATE"
]
}
ECS Task
export taskDefinition=my-consumer-fargate
aws ecs register-task-definition 

--cli-input-json file://my-consumer-fargate-task-definition.json
aws ecs run-task --launch-type FARGATE 

--cluster $clusterName 

--task-definition $taskDefinition 

--network-configuration 

"awsvpcConfiguration={subnets=[subnet-abc], securityGroups=[sg-01]}"
ECS Service
• runs and maintains the required number of tasks
associated with the elastic load balancer

aws ecs create-service --cluster $clusterName 

--service-name my-consumer-service 

--task-definition $taskDefinition 

--desired-count 2 

--launch-type FARGATE 

--network-configuration 

"awsvpcConfiguration={subnets=[subnet-abc], securityGroups=[sg-01]}"
Deploying Updates
1. Build a new image and push it to the repository

2. Create a new revision of the Task Definition

(revision numbers increment automatically)

3. Update Service to use new Task Definition revision

or simply use: https://github.com/silinternational/ecs-deploy 



ecs-deploy -c $clusterName -n my-consumer-service -i $imageURI
Advanced Example of AWS
ECS Deployment with Terraform
VPC with 2 subnets 

(1 public and 1 private)

in each Availability Zone

https://github.com/duduribeiro/terraform_ecs_fargate_example 

https://thecode.pub/easy-deploy-your-docker-applications-to-aws-using-ecs-and-fargate-a988a1cc842f
AWS 

CodeBuild
AWS 

CodePipeline
screenshots from: https://thecode.pub/easy-deploy-your-docker-applications-to-aws-using-ecs-and-fargate-a988a1cc842f
AWS ECS

vs Kubernetes
1. AWS ECS can not be run on-premise

2. AWS ECS lacks advanced features



These two differences can either be seen as weakness or as
strengths.
That's All!

Thank You

More Related Content

What's hot

[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버
[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버
[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버Heungsub Lee
 
도메인 주도 설계의 본질
도메인 주도 설계의 본질도메인 주도 설계의 본질
도메인 주도 설계의 본질Young-Ho Cho
 
실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략YEONG-CHEON YOU
 
Debianの修正はどのように出荷されるか
Debianの修正はどのように出荷されるかDebianの修正はどのように出荷されるか
Debianの修正はどのように出荷されるかHideki Yamane
 
Spring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewSpring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewVMware Tanzu
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbieDaeMyung Kang
 
나만의 엔진 개발하기
나만의 엔진 개발하기나만의 엔진 개발하기
나만의 엔진 개발하기YEONG-CHEON YOU
 
Introduction to OpenStack Trove & Database as a Service
Introduction to OpenStack Trove & Database as a ServiceIntroduction to OpenStack Trove & Database as a Service
Introduction to OpenStack Trove & Database as a ServiceTesora
 
GKE Tip Series how do i choose between gke standard, autopilot and cloud run
GKE Tip Series   how do i choose between gke standard, autopilot and cloud run GKE Tip Series   how do i choose between gke standard, autopilot and cloud run
GKE Tip Series how do i choose between gke standard, autopilot and cloud run Sreenivas Makam
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템QooJuice
 
Understanding performance aspects of etcd and Raft
Understanding performance aspects of etcd and RaftUnderstanding performance aspects of etcd and Raft
Understanding performance aspects of etcd and RaftHitoshi Mitake
 
Dockers and kubernetes
Dockers and kubernetesDockers and kubernetes
Dockers and kubernetesDr Ganesh Iyer
 
HBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseHBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseenissoz
 
Docker introduction for the beginners
Docker introduction for the beginnersDocker introduction for the beginners
Docker introduction for the beginnersJuneyoung Oh
 
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017Amazon Web Services Korea
 

What's hot (20)

Quarkus k8s
Quarkus   k8sQuarkus   k8s
Quarkus k8s
 
[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버
[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버
[야생의 땅: 듀랑고] 서버 아키텍처 - SPOF 없는 분산 MMORPG 서버
 
도메인 주도 설계의 본질
도메인 주도 설계의 본질도메인 주도 설계의 본질
도메인 주도 설계의 본질
 
실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략실시간 게임 서버 최적화 전략
실시간 게임 서버 최적화 전략
 
Debianの修正はどのように出荷されるか
Debianの修正はどのように出荷されるかDebianの修正はどのように出荷されるか
Debianの修正はどのように出荷されるか
 
Redis and Ohm
Redis and OhmRedis and Ohm
Redis and Ohm
 
Spring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewSpring Cloud Data Flow Overview
Spring Cloud Data Flow Overview
 
Packer by HashiCorp
Packer by HashiCorpPacker by HashiCorp
Packer by HashiCorp
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 
나만의 엔진 개발하기
나만의 엔진 개발하기나만의 엔진 개발하기
나만의 엔진 개발하기
 
Introduction to OpenStack Trove & Database as a Service
Introduction to OpenStack Trove & Database as a ServiceIntroduction to OpenStack Trove & Database as a Service
Introduction to OpenStack Trove & Database as a Service
 
GKE Tip Series how do i choose between gke standard, autopilot and cloud run
GKE Tip Series   how do i choose between gke standard, autopilot and cloud run GKE Tip Series   how do i choose between gke standard, autopilot and cloud run
GKE Tip Series how do i choose between gke standard, autopilot and cloud run
 
OpenStack Glance
OpenStack GlanceOpenStack Glance
OpenStack Glance
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Understanding performance aspects of etcd and Raft
Understanding performance aspects of etcd and RaftUnderstanding performance aspects of etcd and Raft
Understanding performance aspects of etcd and Raft
 
Dockers and kubernetes
Dockers and kubernetesDockers and kubernetes
Dockers and kubernetes
 
HBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseHBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBase
 
Docker introduction for the beginners
Docker introduction for the beginnersDocker introduction for the beginners
Docker introduction for the beginners
 
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017
AWS 클라우드 기반 게임 아키텍처 사례 - AWS Summit Seoul 2017
 

Similar to Ruby Microservices with RabbitMQ

AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...
AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...
AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...QCloudMentor
 
Architectures with Windows Azure
Architectures with Windows AzureArchitectures with Windows Azure
Architectures with Windows AzureDamir Dobric
 
Red Hat Open Day JBoss Fuse
Red Hat Open Day JBoss FuseRed Hat Open Day JBoss Fuse
Red Hat Open Day JBoss FuseAdrian Gigante
 
apachekafka-160907180205.pdf
apachekafka-160907180205.pdfapachekafka-160907180205.pdf
apachekafka-160907180205.pdfTarekHamdi8
 
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDB
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDBWebinar: Enabling Microservices with Containers, Orchestration, and MongoDB
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDBMongoDB
 
RabbitMQ and AMQP with .net client library
RabbitMQ and AMQP with .net client libraryRabbitMQ and AMQP with .net client library
RabbitMQ and AMQP with .net client libraryMohammed Shaban
 
3 f6 9_distributed_systems
3 f6 9_distributed_systems3 f6 9_distributed_systems
3 f6 9_distributed_systemsop205
 
An introduction to Apache Camel
An introduction to Apache CamelAn introduction to Apache Camel
An introduction to Apache CamelKapil Kumar
 
Enterprise Messaging with RabbitMQ.pdf
Enterprise Messaging with RabbitMQ.pdfEnterprise Messaging with RabbitMQ.pdf
Enterprise Messaging with RabbitMQ.pdfOrtus Solutions, Corp
 
Building an Event Bus at Scale
Building an Event Bus at ScaleBuilding an Event Bus at Scale
Building an Event Bus at Scalejimriecken
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices💡 Tomasz Kogut
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with DockerGiuseppe Piccolo
 
Software Architectures, Week 4 - Message-based Architectures, Message Bus
Software Architectures, Week 4 - Message-based Architectures, Message BusSoftware Architectures, Week 4 - Message-based Architectures, Message Bus
Software Architectures, Week 4 - Message-based Architectures, Message BusAngelos Kapsimanis
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101Huy Vo
 
Beyond REST and RPC: Asynchronous Eventing and Messaging Patterns
Beyond REST and RPC: Asynchronous Eventing and Messaging PatternsBeyond REST and RPC: Asynchronous Eventing and Messaging Patterns
Beyond REST and RPC: Asynchronous Eventing and Messaging PatternsClemens Vasters
 

Similar to Ruby Microservices with RabbitMQ (20)

Microservices deck
Microservices deckMicroservices deck
Microservices deck
 
AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...
AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...
AWS Study Group - Chapter 07 - Integrating Application Services [Solution Arc...
 
Architectures with Windows Azure
Architectures with Windows AzureArchitectures with Windows Azure
Architectures with Windows Azure
 
Red Hat Open Day JBoss Fuse
Red Hat Open Day JBoss FuseRed Hat Open Day JBoss Fuse
Red Hat Open Day JBoss Fuse
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
apachekafka-160907180205.pdf
apachekafka-160907180205.pdfapachekafka-160907180205.pdf
apachekafka-160907180205.pdf
 
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDB
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDBWebinar: Enabling Microservices with Containers, Orchestration, and MongoDB
Webinar: Enabling Microservices with Containers, Orchestration, and MongoDB
 
RabbitMQ and AMQP with .net client library
RabbitMQ and AMQP with .net client libraryRabbitMQ and AMQP with .net client library
RabbitMQ and AMQP with .net client library
 
3 f6 9_distributed_systems
3 f6 9_distributed_systems3 f6 9_distributed_systems
3 f6 9_distributed_systems
 
An introduction to Apache Camel
An introduction to Apache CamelAn introduction to Apache Camel
An introduction to Apache Camel
 
Enterprise Messaging with RabbitMQ.pdf
Enterprise Messaging with RabbitMQ.pdfEnterprise Messaging with RabbitMQ.pdf
Enterprise Messaging with RabbitMQ.pdf
 
Building an Event Bus at Scale
Building an Event Bus at ScaleBuilding an Event Bus at Scale
Building an Event Bus at Scale
 
Kafka tutorial
Kafka tutorialKafka tutorial
Kafka tutorial
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Spring RabbitMQ
Spring RabbitMQSpring RabbitMQ
Spring RabbitMQ
 
Containing the world with Docker
Containing the world with DockerContaining the world with Docker
Containing the world with Docker
 
Software Architectures, Week 4 - Message-based Architectures, Message Bus
Software Architectures, Week 4 - Message-based Architectures, Message BusSoftware Architectures, Week 4 - Message-based Architectures, Message Bus
Software Architectures, Week 4 - Message-based Architectures, Message Bus
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
Beyond REST and RPC: Asynchronous Eventing and Messaging Patterns
Beyond REST and RPC: Asynchronous Eventing and Messaging PatternsBeyond REST and RPC: Asynchronous Eventing and Messaging Patterns
Beyond REST and RPC: Asynchronous Eventing and Messaging Patterns
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Ruby Microservices with RabbitMQ

  • 2. Content • Intro
 from monolith decoupling to microservices integration • The Main Part
 microservices messaging with RabbitMQ/AMQP • Ruby Code Refactoring 
 from ActiveRecord Callback to Consumer as a Microservice • A Simple Microservice Deployment
 in docker container to AWS ECS
  • 3. Let's start with a bad example
  • 4. A better example ... or can we just publish the event and let subscribed consumers do the work? a complete to-do list for this event
  • 5. Decoupling Publisher / Producer Subscriber / Consumer Subscriber / Consumer Subscriber / Consumer
  • 6. Monolith vs Microservices vs Complexity in
 Interactions Code
 Complexity
  • 7. Microservice • a small program that handle one task • independently deployable • work together by communicating so that can accomplish the larger task • integrated system on the whole provides value https://martinfowler.com/ articles/microservices.html https://youtu.be/wgdBVIX9ifA
  • 8. App Integration Options • File Transfer • Shared Database • Remote Procedure Invocation • Messaging While all four approaches solve essentially the same problem,
 each style has its distinct advantages and disadvantages. http://www.enterpriseintegrationpatterns.com/patterns/messaging/IntegrationStylesIntro.html
  • 9. File Transfer Consumer A Consumer B Consumer C DATA
 FILE Producer Export Import
  • 10. Shared Database Consumer A Consumer B Consumer C Producer DB
  • 11. Remote Procedure Invocation Consumer A Consumer B Consumer C Producer Call Result
  • 12. Messaging Exchanges Bindings Queues Consumer A Consumer B Consumer C Producer AMQP 0-9-1 Message Broker
  • 13. • a binary, networking protocol with minimal overhead • originated in 2003 by John O'Hara at JPMorgan Chase • version 0.9.1 was specified in 2008 • in 2011 OASIS standards group change it to a significantly different beast
  • 14. AMQP 0-9-1 • virtual host is a logical partition within the server 
 (a multi-tenant system similar to virtual hosts in Apache/Nginx) • each of virtual hosts can have many connections, channels, queues, exchanges and some other things • bindings binds an exchange to a queue or many queues • exchange can be: direct, fanout, with topic or headers • queue is a buffer that holds messages on behalf of a consumer (or consumers)
  • 15. The Producer • external application which creates messages and decides: • how the attributes should be configured for routing • from which exchange the messages should start from • what is the actual payload that is being sent
  • 16. The Message • an atomic unit of processing • consists of: • content (body, bare message or payload) • attributes - metadata about the message like content type, encoding, routing key, whether the message will be persistent or not, and whether it has a priority level, etc. • is created (published) by the producer • may go through more than one exchange before landing in the right queue
  • 17. The Exchange • Direct exchange route messages based on an exact match with the specified routing key • Fanout exchange automatically route the message to all the queues known to them (ignores the routing key) • Topic exchange pattern match on the routing key (topic) to route the messages • Header exchange use the message header attributes for matching the queue • Default (anonymous) exchange is a direct exchange (created automatically) which routes messages with empty exchange name - it compares routing key with the queue name
  • 18. Multiple Queues and Consumers Consumer A Queue 1 Queue 2 Queue 3 Consumer B Consumer C
  • 19. The Consumer • external application which is subscribed to one or more queues • alerted whenever a message shows up in the subscribed queue • can poll the queue at regular intervals to see which messages were added in the queue since the last time it made the request • can send acknowledgments back to RabbitMQ that the message has been: • received (known as ack), or • rejected (nack for negative acknowledgments)
  • 20. Bindings • Routing Key • Publisher: exchange.publish(payload, routing_key: 'foo') • Queue Binding: queue.bind(exchange, routing_key: 'foo') • Headers • Publisher: exchange.publish(payload, headers: { ... }) • Queue Binding: queue.bind(exchange, arguments: { ... })
  • 21. • an message broker implemented with Erlang/OTP • implements all the AMQP 0.9.1 concepts:
 messages, queues, exchanges, bindings, virtual hosts ... • ... and with plugins for other messaging protocols such as
 STOMP, XMPP, and more • has fantastic client support in a variety of popular languages: Ruby, Python, Java, PHP, C#, JavaScript, Go, Elixir, Objective-C, Swift, ...
  • 22. Gems • Bunny - AMPQ client for Ruby (MRI) • March Hare - AMPQ client for JRuby • Sneakers - a background consumer/worker • Hutch - asynchronous inter-service communication • RabbitMQ HTTP API client (various management features) • Ruby RabbitMQ Clients Blog: http:// blog.rubyrabbitmq.info/
  • 23. Features • No message loss • Persistent Messages • Publisher Confirms • Message Acknowledgment • Mirrored Queues • Message Ordering • Dead Letter Exchanges • Alternate Exchanges • Message and Queues TTLs • Consumer Priorities • Federation ... and many more
  • 24. Back to Refactoring ... or can we just publish the event and let subscribed consumers do the work?
  • 32. Messaging Patterns (65) Creative Commons Attribution 4.0 license.http://www.enterpriseintegrationpatterns.com/patterns/messaging/index.html
  • 33. Microservice Messaging Benefits • language-agnostic • amplifies loose-coupling • makes scaling and rearchitecting simpler • better reliability and availability - messages will be waiting until the consumer is ready to process them • multiple communication patterns: events, message/reply, notification, async request-response, pub/sub, etc.
  • 34. Microservice Messaging Drawbacks • introducing new complexity into the system 
 (the message broker) • a failure in the message broker can cause severe effects on the system (highly-available message broker) • big messages can cause network congestion • "eventual data consistency" (instead of immediate consistency across different microservices)
  • 36. Installing Docker CE on Workstation • macOS: https://store.docker.com/editions/community/docker-ce- desktop-mac • Linux Ubuntu: https://store.docker.com/editions/community/docker-ce- server-ubuntu • or any other Linux distro: https://store.docker.com/search? offering=community&operating_system=linux&type=edition
  • 37. My Ruby Project Structure
  • 40. Elastic Container Registry export repositoryName=my_consumer 
 export repositoryURI=123456789012.dkr.ecr.us-east-1.amazonaws.com 
 export containerName=my_consumer 
 export ver=1.0.0
 export imageURI=$repositoryURI/$repositoryName:$ver aws ecr create-repository --repository-name $repositoryName eval $(aws ecr get-login --no-include-email) docker tag $containerName:$ver $imageURI docker push $imageURI
  • 41. Elastic Container
 Service (ECS) • logical way to group resources (Tasks and Services) • currently provides two launch types: • EC2 • Fargate (abstract away EC2 instances) collection of ECS resources: https://github.com/nathanpeck/awesome-ecs export clusterName=staging
 aws ecs create-cluster --cluster-name $clusterName
  • 42. ECS Cluster
 Building Blocks Task Definition • specify the resources for a Docker container or group of containers, such as:
 docker image (registry), ports, CPU/RAM, logs, any volumes, environment variables, etc. Task • running containers according to the Task Definition (one-off or long-running) • TaskRole allow access to S3, DynamoDB, etc. Service • manage long-running tasks (defines desired count and replace failed containers) • integrates with Elastic Load Balancer
  • 43. ECS Task Definition { "containerDefinitions": [ { "command": [ "bin/worker" ], "workingDirectory": "/app", "essential": true, "image": $imageURI, "logConfiguration": { "logDriver": "awslogs" }, "name": $containerName } ], "cpu": "256", "memory": "512", "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole", "family": "my-consumer-fargate", "networkMode": "awsvpc", "requiresCompatibilities": [ "FARGATE" ] }
  • 44. ECS Task export taskDefinition=my-consumer-fargate aws ecs register-task-definition 
 --cli-input-json file://my-consumer-fargate-task-definition.json aws ecs run-task --launch-type FARGATE 
 --cluster $clusterName 
 --task-definition $taskDefinition 
 --network-configuration 
 "awsvpcConfiguration={subnets=[subnet-abc], securityGroups=[sg-01]}"
  • 45. ECS Service • runs and maintains the required number of tasks associated with the elastic load balancer
 aws ecs create-service --cluster $clusterName 
 --service-name my-consumer-service 
 --task-definition $taskDefinition 
 --desired-count 2 
 --launch-type FARGATE 
 --network-configuration 
 "awsvpcConfiguration={subnets=[subnet-abc], securityGroups=[sg-01]}"
  • 46. Deploying Updates 1. Build a new image and push it to the repository 2. Create a new revision of the Task Definition
 (revision numbers increment automatically) 3. Update Service to use new Task Definition revision or simply use: https://github.com/silinternational/ecs-deploy 
 
 ecs-deploy -c $clusterName -n my-consumer-service -i $imageURI
  • 47. Advanced Example of AWS ECS Deployment with Terraform VPC with 2 subnets 
 (1 public and 1 private)
 in each Availability Zone https://github.com/duduribeiro/terraform_ecs_fargate_example 
 https://thecode.pub/easy-deploy-your-docker-applications-to-aws-using-ecs-and-fargate-a988a1cc842f
  • 48. AWS 
 CodeBuild AWS 
 CodePipeline screenshots from: https://thecode.pub/easy-deploy-your-docker-applications-to-aws-using-ecs-and-fargate-a988a1cc842f
  • 49. AWS ECS
 vs Kubernetes 1. AWS ECS can not be run on-premise 2. AWS ECS lacks advanced features 
 These two differences can either be seen as weakness or as strengths.