Showing posts with label HAProxy. Show all posts
Showing posts with label HAProxy. Show all posts

Sunday, August 18, 2013

Load Balancing in Amazon Web Services


Load balancing is one of the most important technique to be followed for architecting highly scalable and available applications on AWS cloud. Keeping this in mind, I have compiled my experience and articles i have written on this subject as "Load balancing on AWS" series.  

Dissecting Amazon Elastic Load Balancing : Amazon ELB is dissected into 18+ points and analysed based on the production implementation experience. This article is a must read for all Amazon ELB users who wants to understand in detail what ELB can do and what are some of the road blocks you can face sometimes when using Amazon ELB. Click here for the article.  

Amazon ELB Multi region migration checklistAmazon Elastic Load Balancing has a Amazon EC2 Regional scope. It needs to be migrated to alternate Amazon EC2 region in event of DR or during new migration setup . I am sharing my experience in this post as few checklists/areas that needs to be taken care during this Amazon ELB migration to alternate EC2 region. Refer Article

Amazon ELB Implementation Architectures : Amazon ELB can be implemented in variety of architectures in your AWS cloud. Some of them are real bad cases and some of them follow best practices. If you want to understand the common implementation architectures and its pro's/con's refer this article  

Comparison Analysis between Amazon ELB and HAProxy:  HAProxy is a popular OSS software load balancer widely used in Amazon Cloud Infrastructure. This article provides a detailed comparison between the two and analyzes where both of them stand. This article is featured in the HAProxy web site as well. Click here for the article

Architecting High Availability @ HAProxy Load Balancing Tier: Not all the times Amazon ELB is used as the choice of load balancer in Amazon Web Services. But deploying an OSS load balancer in AWS has got is own set of considerations and high availability is one of them. In this post i explore how to design High Availability @ HAProxy load balancing layer. Refer Article

Architecting Highly Available Web App Layer using HAProxy Load Balancing : In this post we explore four options of Load balancing Web/App Tier using HAProxy in AWS. Refer Article

Configuring Citrix NetScaler Load Balancing on AWSCitrix NetScaler is a popular Load balancer in the Enterprise world. Hardware and virtualized NetScaler has been serving many popular enterprise online assets for years. How to configure Citrix Netscaler based Load Balancing in AWS is explained in this post. Refer Article

Load Balancing Amazon RDS Read Replica's using HAProxyIn this post, let us explore how HAProxy can be used to solve load balancing between RDS Read Replica's in Amazon Cloud.Refer Article

Choosing right HAProxy- Amazon EC2 Instance Types and AMI Types for load balancingBefore choosing optimal Amazon EC2 instance Type for HAProxy Load balancing layer in AWS we need to minimum understand some important factors involved. Refer Article 

Configuring Amazon ELB and understanding the parameters in detail: Amazon provides a detailed documentation on how to configure ELB. In this article i have detailed the configuration steps with detailed understanding on the parameters and its implications. Must read of Amazon ELB newbies. Click here for the article 

Web Session Synchronization patterns in AWS: Architectures for synchronizing sessions of load balanced Web/App EC2 is detailed in this post. Refer Article

Geo Distributed Load Balancing using Route53 and Amazon ELB: Some customers would have Geo Distributed their architecture across multiple Amazon EC2 regions. In this article we explore why do we need Geo Distributed architecture, Cost of Latency and how to achieve it using Route 53 + Amazon ELB. Click here for the article

Deeper Health Checks and Problems in Load Balancing in AWSHealth Checks are one of the essential mechanisms that helps you to keep N-Tiered system highly available.This sounds simple and straight forward right, but some of the customers i have consulted follow a much deeper Health check diagnostic mechanism and it might have problems when migrated to AWS cloud. Let us explore this case in detail in this post. Refer Article

Configuring Amazon ELB With SSL offloading: How to configure SSL with Amazon ELB. Click here for the article What are the benefits of offloading SSL in Amazon ELB. Here

Monitoring Amazon ELB using Amazon CloudWatch and understanding the result and metrics

Why do we need Amazon Elastic Load Balancing and What are its benefits ?

Saturday, August 3, 2013

Load Balancing Amazon RDS Read Replica's using HAProxy


When you are architecting a read intensive online application in AWS cloud you can employ techniques like CDN, Caching etc to improve the overall concurrency and performance of the application. One of the age old techniques applied is also scaling out the Database Read Slaves. To solve this need, Amazon RDS MySQL has a concept of Master and Read Replica Slaves. Depending upon the read intensity and concurrency needed, you can scale out and add more read replica slaves to the Master RDS MySQL. Ideally 1 to 5 Read replica slaves can be placed with RDS MySQL master for performance. If more than 5 Read Replica Slaves are required, it surely sounds like a bad design because of the load it puts on the master, replication lag and overall manageability of this tier itself. I would suggest you need to functionally partition your database or use some other high performance/scale out data stores like caching, MongoDB, DynamoDB, Redis etc in your architecture to over come this. 
Now let us define a common architecture deployment pattern for read intensive site:

  • Entire setup is inside Amazon VPC
  • Your Web App is deployed in Amazon Auto Scaling Mode.
  • You have 2 or more RDS Read replica slaves with your RDS Master. This is good, now the question is how do you load balance requests between your Read replica's, What happens when you elastically scale out new RDS Read replica's ? 

There are multiple architecture techniques that can be followed to solve this problem from embedding Load balancing plugins in PHP, to introducing HAProxy in between etc.
In this post, let us explore how HAProxy can be used to solve this problem in Amazon Cloud.

Architecture 1:  HAProxy as a Separate Tier

  • Web/App EC2 instances are deployed in the public subnet of Amazon VPC in Auto Scaling mode.
  • RDS MySQL Master and 2 Read replica's are deployed in Multiple Subnet - Multi - AZ mode.
  • Programmatic changes, plugins or some ideal mechanism is engineered in the Web/App to separate the Writes and Reads DB.All writes go to Master and reads goes to RDS Read Replica's.
  • Web/App EC2 instances are pointed to HAProxy EC2 address. HAProxy Load balancer is provisioned in a separate tier to load balance internal requests from the Auto Scaled Web/App EC2 instances to the RDS Read Replica EC2's. 
  • Two or more HAProxies are deployed to avoid Single Point of Failure in this tier. 
Below diagram illustrates this architecture technique:
  
Now let us analyse this architecture technique:

  • This is a widely used technique in AWS cloud environment for such problems. You can use this RDS MySQL or MySQL on EC2 as well.
  • New RDS Read replica's can be added and removed elastically depending upon the traffic without modifying the app configuration files. HAProxy configuration entries can be hot deployed
  • Minimum of 2 HAProxy EC2 instances are needed to avoid Single Point of failure in this tier
  • HAProxy can be deployed in Multiple-AZ and Multiple Subnet architecture for better HA 
  • It is recommended to start with m1.large for HAProxy EC2 instances and scale up instance type depending upon traffic/concurrency. Note: m1.small/medium etc have moderate IO bandwidth and may degrade performance between Read replica's and App Tier.
  • Frequent Scale up of HAProxy EC2 to higher instance type might be needed in case hundreds of Web/App EC2 's are auto scaled every day
  • Logic has to be built in App tier to redirect traffic to secondary HAProxy in event of primary HAProxy failure
  • In case both HAProxies are used actively, then logic has to be built in App tier to use both them 
  • Additional price to be paid for 2 or more m1.large HAProxy EC2 instances
  • Additional cost of monitoring and managing this HAProxy Tier

Architecture 2: HAProxy is embedded 

  • Web/App EC2 instances are deployed in the public subnet of Amazon VPC in Auto Scaling mode.
  • RDS MySQL Master and 2 Read replica's are deployed in Multiple Subnet - Multi - AZ mode. 
  • HAProxy is installed/bundled with every Auto Scaled Web/App EC2.
  • Every Web/App EC2 instance is pointed to the local HAProxy itself.  HAProxy will load balance requests from that Auto Scaled Web/App EC2 instances to any of the RDS Read Replica EC2's. 

   
Now let us analyse this architecture technique:
  • This is not widely used as the previous one by many users, probably because not many would have thought/implemented on these lines. But i found this simple and manageable in larger AWS production deployments.
  • New RDS Read replica's can be added and removed elastically depending upon the traffic without modifying the app configuration files. Read Replica endpoints can be propagated to HAProxy using Chef and then hot deployed in HAProxy
  • No single point of failure, if your web/app EC2 instance fails your HAProxy also fails. HAProxy rarely fails individually and is very stable.
  • No additional HAProxy EC2 instances are needed - hence lower cost and ease of manageability.
  • Found this embedded technique really useful in larger, auto scaled AWS production deployments
  • This technique gives more performance when you use larger Web/App EC2 instances like m1.xlarge/ C1.Xlarge etc. HAProxy uses very less CPU and memory and utilizes large IO band with coming with larger instance types. When you have designed your Web/App EC2 with smaller ec2 like medium/small, this is not suggested because of the resource contention
  • Lesser response latency because lesser NW trip
  • No Scale up of HAProxy required. HAProxy is very light weight and super stable process. It can easily scale the requests with your applications need in the embedded model.
  • No complex logic has to be built in web/App tier. they simply contact the HAproxy and it does the rest.


Sample Configuration Steps for Architecture Technique -2:

Setup Details:

  • Web/App EC2 (Amazon Linux) : 2 . (Can be running in amazon auto scaling as well in production) 
  • RDS MySQL Master DB Instance :1
  • RDS MySQL Read Replicas: 2 - 5. (Use Larger EC2 instance types for production purpose)
  • HAProxy will be running on each Web/App EC2
  • Versions,Instance type and configurations used below are strictly for illustrative purposes only. Note: For production use some modifications might be needed. 

Step 1: Creating Read Replicas:
Create two Read Replicas from the RDS MySQL Master DB instance. To create MySQL Read replica navigate to the dashboard of Amazon RDS, select the Amazon RDS MySQL Master and use the option of “Create Read Replica”. On successful creation, you will get endpoint for each of the Read Replica slaves. The below screenshots illustrates the same.






Step 2: Installing HAProxy on Web/App EC2
Installing HAProxy can be done from the source or from the repository. We have installed it from the repository. To install HAProxy from the repository and start it use the following commands,

#yum install haproxy. 
#service haproxy start.

Step 3: HAProxy Configuration on Single Web/App EC2
The configuration file for HAProxy will be available in the following location
 /etc/haproxy/haproxy.cfg
In the configuration file there are many sections like global, default, listen. In each section you may need to specify some parameters and values.
In listen section ,specify port for the RDS MySQL(3306) and user for the mysql-check. "mysql-check" is used to check the health status of the back end read replica nodes. In order for health check to work create an user on RDS MySQL master with no password and use it for the mysql-check user option.This detail will be automatically propogated to read replica's as well. The Load balance algorithm used here is Round Robin. 

Sample configuration file:
##/etc/haproxy/haproxy.cfg##

global

log         127.0.0.1 local2 debug
chroot      /var/lib/haproxy
pidfile      /var/run/haproxy.pid
maxconn     4000
daemon

defaults
mode        tcp
log         global
option tcplog
timeout connect 10000 # default 10 second time out if a backend is not found
timeout client 300000
timeout server 300000
maxconn     20000

# For Admin GUI
listen stats
bind :8080
mode http
stats enable
stats uri /stats

listen mysql *:3306
mode tcp
balance roundrobin
option mysql-check user check
option log-health-checks
server db01 sample-r1.XXXX.amzonaws.com:3306 check port 3306 inter 1000
server db02 sample-r2.XXXX.amazonaws.com:3306 check port 3306 inter 1000

Use the following to create user on master for health check.
use mysql;
create user check;
insert into user (Host,User) values ('<IP/RANGE_OF_HAPROXIES>','check');
FLUSH PRIVILEGES;

flush hosts;

For Production use in Amazon Web Services the HAProxy configuration file and setup can be propagated using Chef.

The Web/App process must be configured to use HAProxy for the MySQL read connections.Once the setup is running, In the admin page of HAProxy you can see the distribution of sessions equally in round robin fashion.
Admin URL Page:


Friday, November 16, 2012

Comparison Analysis:Amazon ELB vs HAProxy EC2



In this article i have analysed Amazon Elastic Load Balancer (ELB) and HAProxy (popular LB in AWS infra) in the following production scenario aspects and fitment:

Algorithms: In terms of algorithms ELB provides Round Robin and Session Sticky algorithms based on EC2 instance health status. HAProxy provides variety of algorithms like Round Robin, Static-RR, Least connection, source, uri, url_param etc. For most of the production cases use Round Robin and Session Sticky is more than enough, But in case you require algorithms like least connection you might have to lean towards HAProxy currently. In future AWS might add this algorithm in their Load Balancer

Spikey or Flash Traffic: Amazon ELB is designed to handle unlimited concurrent requests per second with “gradually increasing” load pattern.  It is not designed to handle heavy sudden spike of load or flash traffic. For example: Imagine an e-commerce website whose traffic increases gradually to thousands of concurrent requests/sec in hours, Whereas imagine use cases like Mass Online Exam or GILT load pattern or 3-Hrs Sales/launch campaign sites expecting 20K+ concurrent requests/sec spike suddenly in few minutes, Amazon ELB will struggle to handle this load volatility pattern. If this sudden spike pattern is not a frequent occurrence then we can Pre-warm ELB else we need to look for alternative Load balancers like HAProxy in AWS infrastructure. If you expect a sudden surge of traffic you can provision X number of HAProxy EC2 instances in running state.

Gradually Increasing Traffic: Both Amazon ELB and HAProxy can handle gradually increasing traffic. But when your needs become elastic and traffic increases in a day, you either need to automate or manually add new HAProxy EC2 instances when the threshold is breached. Also when the load decreases you may need to manually remove the HAProxy EC2 instances from Load Balancing Tier. If you want to avoid these manual efforts you may need to engineer using automation scripts and programs.  Amazon has intelligently automated this elastic problem in their ELB Tier. We just need to configure and use this, that's all.


Protocols : Currently Amazon ELB only supports following protocols: HTTP, HTTPS (Secure HTTP), SSL (Secure TCP) and TCP protocols. ELB supports load balancing for the following TCP ports: 25, 80, 443, and 1024-65535. In case RTMP or HTTP Streaming protocol is needed, we need to use Amazon CloudFront CDN in your architecture. HAProxy can support both TCP and HTTP protocols. In case HAProxy EC2 instance is working in pure TCP mode. A full-duplex connection will be established between clients and servers, and no layer 7 examination will be performed. This is the default mode. It can be used for SSL, SSH, SMTP etc. Current 1.4 version of HAProxy does not support HTTPS protocol natively, you may need to use Stunnel or Stud or Nginx before HAProxy to do the SSL termination. HAProxy 1.5 dev-12 comes with SSL support, it will become production ready soon. 

Timeouts: Amazon ELB currently timeouts persistent socket connections @ 60 seconds if it is kept idle. This condition will be a problem for use cases which generates large files (PDF, reports etc) at backend EC2, sends them as response back and keeps connection idle during entire generation process. To avoid this you'll have to send something on the socket every 40 or so seconds to keep the connection active in Amazon ELB. In HAProxy you can configure very large socket timeout values to avoid this problem. 

White listing IP's :Some Enterprises might want to white list 3rd party Load Balancer IP range in their firewalls . If the 3rd party service is hosted using Amazon ELB it will become a problem. Currently Amazon ELB does not provide fixed or permanent IP address for the Load balancing instances that are launched in its tier. This will be a bottleneck for enterprises which have compulsion to white list the Load balancer IP’s in external firewalls/gateways. For such use cases, currently we can use HAProxy EC2 attached with Elastic IPs as load balancers in AWS infrastructure and white list the Elastic IP's.

Amazon VPC/ Non VPC : VPC- Virtual Private Cloud. Both Amazon ELB and HAProxy EC2 can work inside the VPC and Non VPC environments of AWS.

Internal Load Balancing: Both Amazon ELB and HAProxy can be used for internal load balancing inside VPC. You might provide a service that is consumed internally by the other applications which needs load balancing. ELB and HAProxy can fit in the same. In case internal Load balancing is required in Amazon Non-VPC environments, ELB is not capable currently and HAProxy can be deployed. 

URI/URL based Load balancing: Amazon ELB cannot Load Balance based on URL patterns like other Reverse proxies. Example Amazon ELB cannot direct and load balance between request URLs  www.xyz.com/URL1 and www.xyz.com/URL2. Currently for such use cases you can use HAProxy on EC2.

Sticky problem: This point comes as a surprise to many users using Amazon ELB. Amazon ELB behaves little strange when incoming traffic is originated from Single or  Specific IP ranges, it does not efficiently do round robin and sticks the request to some EC2's only. Since i do not know the ELB internals i assume ELB might be using "Source" algorithm as default for such conditions. No such cases were observed with HAProxy EC2 in AWS unless the balance algorithm is "Source". In HAProxy you can combine "Source" and "Round Robin" efficiently. In case the HTTP request does not have cookie it uses source algorithm, but if the HTTP request has a cookie HAProxy automatically shifts to RR or Weighted. (I will have to check this with AWS team)

Logging: Amazon ELB currently does not provide access to its log files for analysis. We can only monitor some essential metrics using CloudWatch for ELB. We cannot debug load balancing problems, analyze the traffic and access patterns; categorize bots / visitors etc currently because we do not have access to the ELB logs.This will also be a bottleneck for some organizations which has strong audit/compliance requirements to be met at all layers of their infrastructure. In case very strict/specific log requirements are needed, You might need to use HAProxy on EC2, in case it suffices the need. 

Monitoring: Amazon ELB can be monitored using Amazon CloudWatch. Refer this URL for ELB metrics that can be currently monitored: http://harish11g.blogspot.in/2012/02/cloudwatch-elastic-load-balancing.html. CloudWatch+ELB is detailed for most use cases and provides consolidated result of the entire ELB tier in console/API. On the other hand HAProxy provides user interface and stats for monitoring its instances. But if you have farms(20+) of HAProxy EC2 instances it becomes complex to manage this monitoring part efficiently. You can use tools like ServerDensity to monitor such HAProxy farms, but it has huge dependency on NAT instances availability for inside Amazon VPC deployments.

SSL Termination and Compliance requirements:
SSL Termination can be done at 2 levels using Amazon ELB in your application architecture .They are
  • SSL termination can be done at Amazon ELB Tier, which means connection is encrypted between Client(browser etc) and Amazon ELB, but connection between ELB and Web/App EC2 is clear. This configuration may not be acceptable in strictly secure environments and will not pass through compliance requirements.
  • SSL termination can be done at Backend with End to End encryption, which means connection is encrypted between Client and Amazon ELB, and connection between ELB and Web/App EC2 backed is also encrypted. This is the recommended ELB configuration for meeting the compliance requirements at LB level. 
HAProxy 1.4 does not support SSL termination directly and it has to be done in Stunnel or Stud or Nginx layer before HAProxy. HAProxy 1.5 dev-12 comes with SSL support, it will become production ready soon, i have not yet analyzed/tested the backend encryption support in this version.

Scalability and Elasticity : Most important architectural requirements of web scale systems are scalability and elasticity. Amazon ELB is designed for this and handle these requirements with ease.Elastic Load Balancer does not cap the number of connections that it can attempt to establish with the load balanced Amazon EC2 instances.Amazon ELB is designed to handle unlimited concurrent requests per second. ELB is inherently scalable and it can elastically increase /decrease its capacity depending upon the traffic. According to a benchmark done by RightScale, Amazon ELB was easily able to scale out and handle 20K+ or more concurrent requests /sec. Refer URL:http://blog.rightscale.com/2010/04/01/benchmarking-load-balancers-in-the-cloud/
Note: The load testing was stopped after 20K req/sec by RightScale because ELB kept expanding its capacity. Considerable of DevOps engineering is needed to automate this functionality with HAProxy.

High Availability: Amazon ELB is inherently fault tolerant and a Highly available service. Since it is a managed service, Unhealthy load balancer instances are automatically replaced in ELB tier. In case of HAProxy, you need to do this work yourself and build HA on your own. Refer URL http://harish11g.blogspot.in/2012/10/high-availability-haproxy-amazon-ec2.html to understand more about High Availability @ Load Balancing Layer using HAProxy.

Integration with Other services: Amazon ELB can be configured with work seamlessly with Amazon AutoScaling, Amazon CloudWatch and Route 53 DNS services. The new web EC2 instances launched by Amazon AutoScaling are added to the Amazon ELB for Load balancing automatically and whenever load drops; existing EC2 instances can be removed by Amazon Auto Scaling from ELB. Amazon AutoScaling and CloudWatch cannot be integrated seamlessly with HAProxy EC2 for this functionality. But HAProxy can be integrated with Route53 easily for DNS RR/Weighted algorithms.   

Cost: If you run a ELB in US-East Amazon EC2 region for a month (744 hrs) processing close to 1 TB of data, it will cost around ~26 USD (ELB usage+Data charge).  In case if you use HAProxy (2 X m1.large EC2 for HAProxy, S3 backed AMI, Linux instances, No EBS attached) as base capacity and add upto 4 or more m1.large EC2 depending upon traffic. It will minimum cost 387 USD for EC2 compute + Data Charges to start with. it is very clear and evident that larger deployments can save lots of cost and immensely benefit using Amazon ELB compared to HAProxy on EC2.  

Saturday, October 27, 2012

High Availability @ Load Balancing Layer-HAProxy / ELB


Architecting High Availability at the Load Balancing layer is one of the important aspects in the web scale systems in AWS. We can follow multiple strategies for achieving the same. I am listing some of the designs for achieving the same.

Pattern 1: Route 53 DNS RR + HAProxy

Route53 is a Managed DNS service provided by Amazon Web Services. Route 53 supports Round robin and weighted algorithms. If the Route53 DNS server has several entries for a given hostname, it will return all of them in a rotating order. This way, various users will see different addresses for the same name and will be able to reach different EC2 instances in LB Tier.

$ host -t a HAProxyTestXYZ.com
HAProxyTestXYZ.com. has address 50.19.82.183 (Primary EIP)
HAProxyTestXYZ.com. has address 23.23.174.254 (Secondary EIP)



Example, if we attach the Elastic IP’s of 2 HAProxy EC2 instances under the Route 53, both the IP’s are sent to the user browsers by the Route 53 DNS. In case, the algorithm configured is Round Robin at the Route 53 level, then browser- 1 will get EIP-1(50.19.82.183) of HAProxy-1 as the primary IP and browser -2 will get EIP-2 (23.23.174.254) of HAProxy-2 as the primary IP in rotation basis.  The browser- 1 will contact the HAProxy-1 and in case HAProxy-1 is not reachable it will contact the secondary EIP which is HAproxy-2 and so forth. This is an age old technique generally used by search engines, content servers (or) web scale systems for achieving scalability in LB layer. But this method does not provide any means of High availability @ LB layer. It requires additional measures to permanently check the HAProxy EC2 LB instances status and switch a failed EC2 instance EIP to another HAProxy EC2 LB. For this reason, this pattern is generally used as a complementary solution in High Availability, not as a primary one.  For achieving better stability at this layer in AWS, I usually recommend having 2 or more HAProxies distributed on multiple AZ’s inside the Amazon EC2 region. This way if one of the HAProxy is down, the website still functions with the help of other HAProxies and even if the entire Amazon EC2 AZ is down still the HAProxies in the other AZ can handle the requests and keep the website active. Some load tests have proven that HAProxy on m1.large EC2 instance can handle close to ~4500+ HTTP requests/second. So depending upon the number of concurrent requests/sec needed on your application you can go ahead and attach multiple HAProxy EC2 instances to the Route 53. Now that we achieved availability horizontally using the Route53 DNS Round Robin in HAProxy layer let us try to understand the intricacies behind this architecture.  Since we now have 2 or more HAProxies what will happen to the contextual web sessions data that resides in the application servers. HAProxies need to know in which application server the session data of the user resides else the requests will have authorization failures.

There are 2 architecture designs we can follow for solving this contextual problem they are:

Stateless Application design:  This is the recommended and widely used design. The web session data is separated out from the Web/App server memory and they are kept in common cache stores like MemCacheD, TerraCotta etc. Refer this URL to understand common patterns followed in AWS: http://harish11g.blogspot.in/2012/10/web-session-synchronization-aws-ec2.html
Since the session data is now kept in a common store like MemCacheD, HAProxies can direct their requests to any of the web/app servers attached under it without knowing where the session state is mapped. Whenever any web/app server receives the request from any of the HAProxies, it will validate and authorize the session data from the common store.  In event of any HAProxy or Web/App EC2 failure still the website functions without problems because other HAProxies and Web/App servers are still able to handle the subsequent requests. Thus we achieve availability and scalability on the HAProxy/Load Balancing layer following this model.

Sticky Application design: Things are usually not ideal and the way we assume to be in real world. Some applications are still designed with stateful nature and they store the session data, cache data etc. in their web/app server memory.  We can always recommend the application teams to re-architect this model to stateless, but not always this suggestion works for short term migrations, inter dependencies etc.  So as architects we need to find way to live and cope up with this design and still try to achieve availability on the load balancing layer. HAProxy follows a technique called as “Cookie Learning” and “Cookie Insertion” to help state full applications. HAProxy can be configured to learn the application cookie ("JSESSIONID"), when HAProxy receives the user's request, it checks if it contains this particular cookie and a known value. If this is not the case, it will direct the request to any Web/App EC2 server, according to the load balancing algorithm configured. HAProxy will then extract the cookie value from the response and add it along with the server's identifier to a local table. When the user request comes back again, the load balancer sees the cookie, lookups the table and finds the Web/App EC2 server to which it forwards the request. Let me detail this important flow a little bit;
HAProxy-1 EC2 instance will receive client’s requests from the browser. If a request does not contain a cookie, it will be forwarded to a valid Web/App EC2 Instance Apache-A. In return, if a JESSIONID cookie is seen, the Web/App EC2 Instance name (Example “A”)will be prefixed into it, followed by a delimiter ('~') like "JSESSIONID=A~xxx".When the browser client requests again with the cookie  JSESSIONID=A~xxx", HAProxy-1 will know that it must be forwarded to Web/App Instance Apache-A. The EC2 Instance name ”A” will then be extracted from cookie before it is sent to the Web/App EC2 Instance Apache-A.
If Web/App EC2 Instance Apache-A dies, then requests will be sent to another valid server Web/App EC2 Instance Apache-B by LB and the cookie will be reassigned.
If HAProxy-1 itself dies, then requests will be sent to HAProxy-2 which will identify the Web/App EC2 instance to forward the request. This way even if the subsequent requests moves from HAProxy-1 to HAProxy-2 in event of HAProxy-1 failure, still the requests are sent to the same Web/App instance Apache-A by the cookie learning/insertion mechanism of HAProxy.

Sample HAProxy Settings to achieve this
listen webfarm 192.168.1.1:80
       mode http
       balance roundrobin
       cookie JSESSIONID prefix
       option httpclose
       option forwardfor
       option httpchk HEAD /index.html HTTP/1.0
       server Apache-A 192.168.1.11:80 cookie A check
       server Apache-B 192.168.1.12:80 cookie B check

Note: You can use more sophisticated DNS services like UltraDNS , DNSMadeEasy etc also in this architecture to better control the Load balancing and traffic direction at the DNS level. 

Pattern 2: Route 53 DNS RR + HAProxy in Active-Passive mode

This is an extension of the Route53 DNS RR pattern and everything discussed in the previous pattern still applies to this context. In addition to associating HAProxies horizontally under Route53, we will build availability for every HAProxy vertically as well in this pattern. High Availability is built taking into consideration HAProxy process failure and HAProxy EC2 instance failure.

2 or more HAProxies from multiple AZ’s are taken and they are attached with Amazon Elastic IP’s. These Elastic IP’s are then associated in Route 53 with DNS RR. These HAProxies are now “Active” and are ready to handle the user requests. For HA, another equivalent set of HAProxies are launched in the respective AZ’s as “Standby”. In event of the “Active” HAProxy failure, the Standby HAProxy remaps to the same Amazon Elastic IP takes over the subsequent requests from the client.



In the above diagram, there are 2 HAProxies in “Active” state with Elastic IP’s 50.19.82.183 & 23.23.174.254. They are deployed across Multiple Availability Zones inside an Amazon EC2 region. Another 2 HAProxies are launched in respective AZ’s, but they are kept idle in “Standby” state. In event of HAProxy-1 (EIP: 50.19.82.183) failure the Elastic IP is remapped to Standby HAProxy-3 in the same AZ. The remapping takes ~60 seconds and the HAPorxy-3 will be handling the subsequent requests directed by the browsers to the 50.19.82.183 IP.

Broadly there are 2 levels of failure in this pattern;

Failure @ HAProxy Process level
Failure @ HAProxy EC2 instance level



Failure @HAProxy Process level:  When HAProxy Process at the “Active” server fails; we can detect this using KeepAliveD and switch the Elastic IP from Active -> Standby. We have observed it takes ~60-120 seconds for the standby to takeover. During this time the particular HAProxy alone will be unreachable. KeepAliveD script is configured in both the Active and standby HAProxy EC2 instance. KeepAliveD implements a set of checkers to dynamically and adaptively maintain and manage load balanced server pool according to their health. High availability is achieved by Virtual Router Redundancy Protocol VRRP protocol of the KeepAliveD. Since Amazon EC2 currently does not support Multicast protocol we need to configure KeepAliveD with Unicast TCP in this scenario.  For more details refer http://www.keepalived.org/. Mean time manually we can bring the failed HAProxy Process up and make this as the new standby.

Script Name: “/etc/keepalived/keepalived.conf”


vrrp_script chk_haproxy {           # Requires keepalived-1.1.13
script "killall -0 haproxy"     # cheaper than pidof
interval 20                      # check every 2 seconds
weight 20                        # add 2 points of prio if OK
}
vrrp_instance VI_1 {
interface eth0
state MASTER
virtual_router_id 51
ipriority 101                    # 101 on master, 100 on backup
vrrp_unicast_bind 10.215.31.4
      #internal IP address of EC2 instance 01
vrrp_unicast_peer 10.85.110.252
  #internal IP address of EC2 instance 02
notify_master "/etc/keepalived/vrrp.sh"
track_script {
chk_haproxy weight 20
}
}

Script Name: /etc/keepalived/vrrp.sh
#vrrp.sh
#!/bin/bash
cd /opt/aws/apitools/ec2/bin
#DisAssociate EIP from this instance.
./ec2-disassociate-address --aws-access-key XXXXXXX –aws-secret-key XXXXXXX  [EIP]
#Mapping EIP to secondary server
./ec2-associate-address --aws-access-key XXXXXXX  –aws-secret-key XXXXXXX  [EIP] -i [ec2_instance_id_of_primary_or_secondary]



Failure @ HAProxy EC2 instance level: When the Active HAProxy EC2 instance itself fails; we can detect this using Heartbeat and switch the Elastic IP from Active -> Standby. "Heartbeat" tool connects two servers and checks the regular "pulse" or "heartbeat" between them. The standby server takes over the work of the “Active” as soon as it detects an alteration in the "heartbeat" of the former. We have observed it takes ~120+ seconds for the standby to takeover. During this time the particular HAProxy alone will be unreachable. Heartbeat has to be configured in both the Active and standby HAProxy EC2 instance. Since Amazon EC2 currently does not support Multicast protocol we need to configure Heartbeat with Unicast UDP in this scenario. Mean time manually we can bring the failed HAProxy EC2 instance up and make this as the new standby.

Script Name: /etc/ha.d/ha.cf
logfile /var/log/ha-log
logfacility local0
keepalive 2
deadtime 30
initdead 120
udpport 694
ucast eth0 xx.xxx.xxx.xxa #Internal IP of EC2 instance 01
ucast eth0 xx.xxx.xxx.xxb #Internal IP of EC2 instance 02
auto_failback off


Script Name: Create a script named “elastic_ip” in both the servers.
#!/bin/bash
I_ID="[ec2_instance_id" # different for each EC2 servers.
ELASTIC_IP="X.X.X.X"
case $1 in
    start)
ec2-associate-address --aws-access-key XXXXX --aws-secret-key XXXXX "$ELASTIC_IP" -i "$I_ID" > /dev/null
       echo $0 started
       ;;
    stop)
ec2-disassociate-address --aws-access-key XXXXX --aws-secret-key XXXXX "$ELASTIC_IP" > /dev/null
    echo $0 stopped
       ;;
    status)
ec2-describe-addresses --aws-access-key XXXXX --aws-secret-key XXXXX | grep "$ELASTIC_IP" | grep "$I_ID" > /dev/null
    # grep will return true if this ip is mapped to this instance
    [ $? -eq 0 ] && echo $0 OK || echo $0 FAIL
    ;;
esac


Why do we need this redundancy in the HAProxy layer?

Not all the times the DNS RR with LB Cookie Insertion alone is enough for ensuring availability;

Case 1: Imagine you have not automated the scalability @ Load Balancing Layer and one of your Load balancer is down. You do not want to be waked up in the middle of the night rather it is better to have a standby Load Balancer automatically replacing the failed one. Manually you can replace the faulty LB next day.

Case 2: You have a gaming site where long running TCP sockets are established from flash gaming clients to the LB layer. You have planned the capacity of Front end Load Balancers with concurrent connections/sec. Now couple of your Load balancers are down, the new connections will be established to other running LB, but overall your site will now start performing poorly and chances are new connections are exhausted after few hours of heavy traffic. It is better to automatically detect and replace the faulty LB EC2 instance with the standby.

Case 3: Some clients cache the IP address of the Load Balancer, Some of them have long running sticky sessions with web/app, Some hardware devices can take only IP address to push data into the Server infrastructure. Though it is suggested to resolve the IP using DNS, still in reality some use cases does not work the same way.


Pattern 3: Use ELB

Do not worry about all the above patterns, just go and configure Amazon Elastic Load Balancing (ELB). For most of the use cases ELB is more than sufficient.
Amazon Elastic Load Balancer can distribute incoming traffic across your Amazon EC2 instances in a single Availability Zone or multiple Availability Zones. Amazon Elastic Load Balancing automatically scales its request handling capacity in response to incoming application traffic. It can handle 20k+ concurrent requests/sec with ease. It enables you to achieve even greater fault tolerance in your applications, seamlessly providing the amount of load balancing capacity needed in response to incoming application traffic. Elastic Load Balancing detects unhealthy instances within a pool and automatically reroutes traffic to healthy instances until the unhealthy instances have been restored. Any faulty Load balancers in the ELB tier are automatically replaced.
Though for most of the common use cases ELB is more than sufficient in AWS. There are some unique cases which demand the use of Load balancers like HAProxy, Nginx and NetScaler in our architecture in the AWS infrastructure. I will be writing some articles in coming months comparing ELB and others in use case perspectives and context. 



I would like to thank Ramprasad for co-authoring some portions of this article with me. 

Sunday, September 2, 2012

Architecting Highly Available Web App Layer using HAProxy


Option 1: Architecting Web/App Availability-Using HAProxy + AWS Elastic IP 


HAProxy is attached with an AWS Elastic IP(example:50.19.82.183) since it is the entry point to your Web Application. The Elastic IP is assigned to your account and will not change when the Amazon EC2 instance is terminated. We can reuse the same AWS Elastic IP to any other EC2 instance or another HAProxy EC2 in future. The HAProxy Elastic IP is registered Route53 for DNS resolution.
The Web/App EC2’s (imagine Apache EC2 servers) are attached with another series of AWS Elastic IP’s (example:23.23.174.252-255). These Elastic IP’s are configured in the HAProxy configuration file.  In case anyone of the Web/App Apache EC2 goes down, we can manually or automatically spawn a new Web/App EC2 from the Base Golden Image and assign the same Web/App Elastic IP to it again. No Need to change the HAProxy configuration in event of any Web/App EC2 instance failure.






Frequent Sync of Apache Logs and User Uploaded files (if any) to S3 is highly recommended. This will improve the Recovery Point objective and fault tolerance levels of the overall system.

Disadvantages: 
  • Re Mapping an AWS Elastic IP will take around 120 seconds (or more sometimes more depending upon the Region-AZ), some users who have been using the particular Web/App EC2 through that Elastic IP will face problems for few seconds.
  • Additional cost and Data charges incurred for maintain Elastic IP’s
  • This model not suggested for highly scalable systems running hundreds/thousands of Web/App EC2 because of the scarce nature of Elastic IP’s.
  • Fractionally (negligible) slower because of Elastic IP -> Private IP translation
Advantages:  
  • No change in HAProxy Configuration required during Web/App EC2 instance failure.
Sample HAProxy Config (Elastic IP):



Option 2: Architecting Web/App Availability-Using HAProxy + EC2 Private IP's


HAProxy is attached with an AWS Elastic IP(example:50.19.82.183) since it is the entry point to your Web Application. The Elastic IP is assigned to your account and will not change when the Amazon EC2 instance is terminated. We can reuse the same AWS Elastic IP to any other EC2 instance or HAProxy EC2 in future. The HAProxy Elastic IP is registered Route53 for DNS resolution.
The Web/App EC2's (imagine Apache EC2 servers) are accessed with private IP of the Amazon EC2. These private IP's(example:10.62.186.90-93) are configured in the HAProxy configuration file.  In case the Web/App Apache EC2 goes down, we can manually or automatically spawn a new Web/App EC2. Whenever a new EC2 instance is launched their public and private IP’s will change, so we need to hot reconfigure HAProxy file in event of failure with new Web/App Apache EC2 Private IP address assigned.






Frequent Sync of Apache Logs and User Uploaded files (if any) to S3 is highly recommended. This will improve the Recovery Point objective and fault tolerance levels of the overall system.

Disadvantages:
  • Hot reconfigure of HAProxy has to be done whenever the private IP address of Web/App EC2 changes.
Advantages: 
  • No additional cost incurred for accessing through Elastic IP.
  • Fractionally faster because of access using Private IP
Sample HAProxy Config (Private IP):


Option 3: Architecting Web/App Availability-Using HAProxy with Backup Option

HAProxy is attached with an AWS Elastic IP since it is the entry point to your Web Application. The Elastic IP is assigned to your account and will not change when the Amazon EC2 instance is terminated. We can reuse the same AWS Elastic IP to any other EC2 instance or HAProxy EC2 in future. The HAProxy Elastic IP is registered Route53 for DNS resolution.

The Web/App EC2’s (imagine Apache EC2 servers) are grouped into two farms –Active and Backup. X web/app EC2’s are launched in the Active farms. Y more web/app EC2’s are launched in the backup farms. In event of Web/App EC2 failure in the active farms, requests are automatically diverted to the Web/App Apache EC2's in the Backup farms.  Backup farms can have lesser EC2 servers compared to the active farms in case manual/automated recovery can be done faster.  For website outages caused by heavy load traffic, it is better to have both Active and Backup farms in same size to avoid backup failing quickly. All the Web/App EC2 servers in Active and Backup are accessed with private IP's of the Amazon EC2. This private IP is configured in the HAProxy configuration file.  In case an Web/App Apache EC2 goes down, we can manually or automatically spawn a new Web/App EC2. Whenever a new EC2 instance is launched their public and private IP’s will change, so we need to hot reconfigure HAProxy file in event of failure with new Web/App Apache EC2 Private IP address.


Frequent Sync of Apache Logs and User Uploaded files (if any) to S3 is recommended. This will improve the Recovery Point objective.
Disadvantages:
  • It is prohibitively costly to run passive Web/App EC2 in the HAProxy backup mode-You are running a backup farm,keeping it in idle state, paying by hour and using it only when needed( not advisable for clouds). Though this model does not fit the cloud architecture paradigm, i have seen some customers have deployed their Web/App EC2 farm in this fashion. Instead one can adopt Active-Active Web/App EC2 model itself discussed in the next section.
Advantages:  
  • Architecture has High availability built in Web/App EC2 layer. Instant switch between EC2 in Active to Backup farms. Ops have sometime to breathe.
  • RTO and RPO can be efficiently addressed.
  • Only minor advantage i see is version rollouts can be propagated easily. Code rollout first to the Backup farms, Kill the EC2’s in Active Farms and Switch the Active-Backup farms through HAProxy Hot reconfigure. (Note: This scenario can be heavily negated if we start using Puppet /Chef for deployment)
Sample HAProxy Config (Backup Mode):






Option 4: Architecting Web/App Availability-Using HAProxy and AWS Multi-AZ


This is the Recommended architecture for deploying Web/App EC2 under HAProxy inside Amazon for High Availability.
We all know Amazon Web Services Global infrastructure consists of Amazon EC2 Regions. Every Region is designed to be completely isolated from the other Amazon EC2 Region. Every Amazon Region is further sub divided into Availability Zones. By launching EC2 instances in separate Availability Zones (AZ), we can protect our applications from the failure of a single location. To know more about AWS Regions and Availability Zones click here 
In this architecture HAProxy is attached with an AWS Elastic IP and launched in AZ-1.The HAProxy Elastic IP is registered Route53 for DNS resolution.
The Web/App EC2’s (imagine Apache EC2 servers) are launched in 2 or more Availability Zones in the AWS EC2 region. The Private IP addresses of these Web/App EC2 instances are configured in the HAProxy Configuration file. Bringing the Multiple Availability zones into the architecture does not add any extra configuration effort in the HAProxy. 
In event of an Web/App EC2 failure, requests are automatically diverted to the healthy Web/App Apache EC2's in the same or other AZ's (based on LB algorithm). We can manually or automatically spawn a new Web/App EC2 and hot configure their new private IP address into HAProxy.

In event of an entire AZ failure, requests are still automatically diverted to the healthy Web/App Apache EC2's in the other available AZ's (based on LB algorithm). This helps us protect our application from the failure of a single location (Data center) itself and design much more robust HA architecture. 




Frequent Sync of Apache Logs and User Uploaded files (if any) to S3 is recommended. This will improve the Recovery Point objective.
Disadvantages:
  • Data charges between AZ
  • Little complex to maintain because of Multiple EC2 running in active mode
  • No constant NW latency between AZ's makes Web/App EC2 distribution little painful
Advantages:  
  • Architecture has recommended levels of High availability built in Web/App EC2 layer.
  • RTO and RPO can be efficiently addressed.
Sample HAProxy Config (Private IP + Multi-AZ):


Need Consulting help ?

Name

Email *

Message *

DISCLAIMER
All posts, comments, views expressed in this blog are my own and does not represent the positions or views of my past, present or future employers. The intention of this blog is to share my experience and views. Content is subject to change without any notice. While I would do my best to quote the original author or copyright owners wherever I reference them, if you find any of the content / images violating copyright, please let me know and I will act upon it immediately. Lastly, I encourage you to share the content of this blog in general with other online communities for non-commercial and educational purposes.

Followers