Showing posts with label Clustering. Show all posts
Showing posts with label Clustering. Show all posts

Tuesday, April 23, 2013

Apache Solr 4 Cook Book Review

Book Review : Apache Solr 4 Cookbook Review
Author: Rafal Kuc
Reviewed by : Harish Ganesan and Vijay Olety
Book URL : http://www.packtpub.com/apache-solr-4-cookbook/book

Comments : 

I recently read this book and i am really impressed! This book provides good understanding of Apache Solr for both developers as well as consultants.
The book starts off well with an introduction to Apache Solr, the web / app servers required, the role of Zookeeper, why clustering your data is vital ?, the various directory implementations, performance-oriented caching mechanisms, a sample crawler module which coupled with Solr gives a complete end-to-end solution, the role of Apache Tika as a extracting toolkit and the ease of customizing Solr. From then on, the book dwells into the details.
The first step is indexing. It plays a vital part in the entire search solution. Data can be in the form on .txt, .pdf or any other format. It is imperative that all such formats are easily indexable. One of the widely used tools for extracting metadata and language detection is Apache Tika. Data can also be present in a database, for which the Data Import Handler is handy. It comes in two variants – full and delta. Every detail is nicely explained with examples which can make the development time faster. DIH also helps us to modify the data while importing which I felt is a pretty neat feature! One of the nicest features included in Solr 4 is the ability to update single field in a document. I am not sure why this was included in the earlier versions but it’s a classic case of better late than never.
The next step in the pipeline is the data analysis which is achieved through the use of analyzers and tokenizers. Various use cases include elimination HTML and XML tags, copying the contents of one field to another and stemming words amongst others. The detailing that has gone into explaining every concept, the examples and the associated step-by-step explanation is really helpful.
Now that the data is indexed and the data preparation is completed, it’s time to query Apache Solr! Searches can be performed on individual words or on a phrase. You can boost or elevate certain documents over others based on your requirements. Simple concepts such as sorting and faceting of results to complex ones such as ignoring typos using n-grams and detecting duplicates are very simple to understand and perform. Faceting, in particular, is gaining momentum as it helps in implementing the auto-suggest feature and narrowing down the search criteria. A newly introduced feature called the pivot faceting was a much needed one and it vastly simplifies certain use cases related to faceting. Solr provides immense capabilities when it comes to querying and this book explains each of them in great detail taking real-world examples.
We indexed and queried the data. But as our application scales, we have to get our hands dirty and start fine-tuning the performance metrics in order to give a good user experience to our customers. This is where caches and its various flavors and granularities starts to make sense. Cache always plays a major role in any deployment and it is necessary to monitor Solr at all times to gauge its performance. This book can done a great job in clearly explaining the various types of caches, the commit operation and its impact on searchers and how to overcome these. This topic is really important for any Solr real-world deployment and this book has not let me down!
Apache Solr 4.0 introduced the most-awaited SolrCloud feature that allows us to use distributed indexing and searching. Setting up of SolrCloud cluster along with a Zookeeper ensemble to enable replication, fault-tolerance and high availability along with disaster recovery is a piece-of-a-cake now. I really appreciate the time and effort spent on documenting and explaining how to set up two collections inside a single cluster. It was a nightmare to find information on this particular topic when we implementing SolrCloud for one of our customers. But I am rest assured that others referring this book will save precious time of theirs. Adding / deleting nodes from a cluster is no longer a tedious task as the entire process is automated through the presence of Zookeeper nodes. The in-depth knowledge of the author in these topics is clearly visible and is of great help to all the readers. A touch on Zookeeper Rolling Restart, though off-topic, might enable readers to get a complete birds-eye view of the entire cluster. Certain features such as soft commit and NRT search have been explained in detail afterwards (under Real-life Situations) but I felt that at least a mention earlier on would have provided a much needed continuity in that section. For the geeky readers like me, a detailed description about load balancing across shards and replicas and their customizations, if any, would have added an extra amount of spice to this well-cooked food!
As with any other tool, Solr deployment too will run into some kind of a problem. This section details the common problems that are encountered and effective ways to overcome these. Shrinking the size of the index and allocating enough memory in advance amongst others are some of the solutions explained in detail and is clearly documented in this book.
Lastly, as every developer would have wanted it, the real-world scenarios are described and the various Solr concepts that were explained in earlier sections are put together as part of a complete end-to-end solution.
Any one trying Solr 4.0 must read this book in its entirety before recommending a Solr production architecture. As mentioned above, there are a few suggestions which if incorporated in this book would benefit readers. All in all, this book will be really helpful for the developers and consultants alike!


Sunday, April 7, 2013

Cost Saving Tip : Part 4 : Building Amazon ElastiCache Cluster


Amazon ElastiCache has variety of node types and often users end up choosing cheapest instance types and scaling out whenever the cache memory needs increase.  But “Cheap approach may not always be the best and cost effective” in Amazon ElastiCache scenario.Many times it may not be optimal for your requirements in terms of performance and cost and as a customer you may end up paying more because of bad choices. 

In this post we will explore 
  • How to save costs by right sizing the Amazon ElastiCache Clusters/Nodes
  • Analysis approach
  • Tips for savings costs on Amazon ElastiCache
I have taken some sample cache memory requirements and application characteristics, based on that i have explored the economics of choosing a cache node type in Amazon ElastiCache which makes sense.
Following table illustrates the sample cost you will be spending on your Amazon ElastiCache for 100 GB of cache memory size.  Multiply this cost by 10X in case your Cache memory requirements are in TB range. The cost of building 100 GB Amazon ElastiCache cluster using various cache nodes are listed below:



Category 1 Cache Node types for Heavy Utilization
Network IO:  These node types come with High Network IO capacity. They can be used for Cache dependent sites which has heavy cache utilization in terms of requests and data transfer.
Compute utilization: Amazon ElastiCache internally uses memcached engine. Memcached is written using libevent model. This model allows the memcached to scale better with multiple cores, which effectively means better throughput. For applications which needs better concurrency and request throughput it is recommended to plan capacity with multiple cores for cache node types.  The cache nodes under “category-1” have 4-8 cores which are ideally suitable for application which utilizes cache heavily.
Elasticity: Any growing web application has elastic caching needs. In this case, the cache nodes will be added or removed on daily/weekly/monthly basis depending upon the needs. This activity affects the object remapping, node discovery and cache warming process.  Number of existing cache nodes, proportion of addition/removal of cache nodes, cache node type and frequency of addition/removal are some of the parameters that needs to carefully considered and planned during elasticity. Consistent hashing and Auto Discovery are some of the techniques that need to be adopted to minimize the complexity of this action. In general, it is better to build a strategy combining the below points:
  • Proper base node type selection based on the current and project needs. Consolidating them as the cache memory size grows
  • Distribute the data in multiple nodes (more is better than few)
  • Add in smaller proportions with better cache warming procedures

To Deep Dive into Amazon ElastiCache: 


Category 2 Cache Node types for Moderate Utilization
Network IO: Same as Category 1: High IO but depends/regulated upon node types (size).
Compute utilization:  Suitable for moderate workloads. Since cache node types in this category have only 2 cores, they are not suitable of heavy concurrent and compute driven cache access workloads.
Elasticity: All points discussed on category 1 apply here.

Category 3 Node types for Low utilization  
Most of them are Costlier, Some of them are performance wise poor (NW IO and compute) and offers less value for money for bigger cache memory requirements


To know more about Caching Architectures in AWS: 


Economics of choosing Cache Node Types:
From the table we can observe following points in the economics of choosing cache node type:

Tip 1: For a cache memory size requirement of 100 GB cache.m3.2xlarge, cache.m1.xlarge, cache.m2.2xlarge, cache.m2.4xlarge are good candidates. Amazon ElastiCache clusters built with these node types are very good package and offers overall better value to the users in terms of Elasticity, Proportions, Price and Performance
Tip 2: Smaller Cache node types (cache.m1.small) with lower per hour usage price need not be overall cost efficient when your cache memory need grows (~ 100 GB or more)
Tip 3: High CPU EC2 (cache.c1.xlarge) will be the costliest if the cache memory needs grows to GB/TB’s. This cache node type is not a good candidate for most Cache heavy (size) use cases. The only use case I can think of using cache.c1.xlarge when I have ~32 GB of Cache memory requirement which is not elastic and which will be heavily utilized. But anything above 32 GB of cache memory requirement will bleed your cost if you use this node type.
Tip 4: Moderate IO Cache node types (like cache.m3.xlarge, cache.m1.medium, cache.m1.small) are costlier and less efficient compared to High IO peers. You end up paying more if your utilization is heavy in case your cache cluster is composed of Moderate IO Cache node types
Tip 5:The above point emphasizes how important it is choose the right cache node type for cache memory size. Planning the right cache node type according to your current and future requirements helps you save costs. Also I recommend you to consolidate your cache node type periodically till you reach a size of few 100 GB’s to save costs. Post 500 GB, building your cache clusters with High memory Cache node types are usually cost effective. Example: We can see for 100 GB cache, 2 X Cache.m2.4xlarge are sufficient.  But choosing this node type for this cache memory size will not be ideal because of the distribution and churn problems (in case if you are going to expand the memory size frequently). On the other hand if the cache memory size will be increased to or it is 1 TB then building the cache cluster using 15 X Cache.m2.4xlarge makes lots of sense in terms proportion and cost.


Tip for Choosing the Cache Node types: 

Application Characteristics
Cache Node Types
·         Cache dependent application with heavy cache data usage
·         Distributed Cache size:  100 GB -> 1 TB & above
·         Varied message sizes
·         High Concurrency of cache requests
·         Cache nodes will be added or removed on daily/weekly/monthly basis
·         Better performance and value for money

Category 1 Cache node types: Heavy Utilization nodes
cache.m3.2xlarge
cache.m1.xlarge
cache.m2.2xlarge
cache.m2.4xlarge
·         Moderate  Cache dependency & usage
·         Distributed Cache size:  50-100 GB
·         Varied message sizes
·         Moderate concurrency requirements
·         Not very Elastic needs
·         Moderate performance and cost efficient

Category 2 Cache node types: Moderate Utilization nodes
cache.m2.xlarge
cache.m1.large
·         Low Cache dependency & usage
·         Distributed Cache size:  ~50 GB and above
·         Small message sizes
·         Low concurrency requirements
·         Not very Elastic needs
·         Moderate performance and I am ready for $$$ leakage when memory needs grow
Category 3 Cache node types: Low Utilization nodes
cache.m3.xlarge
cache.m1.medium
cache.m1.small
cache.c1.xlarge

Saturday, October 6, 2012

Web Session Synchronization patterns in AWS


Statelessness is an important property that every application needs to posses in order to achieve Scalability and Availability in AWS cloud. Usually any web application will maintain the user web sessions on its server side to authorize them at every request. Also Sessions are used map the user requests to user data in some designs. When developing a new PHP/Java application, a common approach is to store session data in memory. Unfortunately, this approach doesn't scale very well for Large scale distributed systems . The moment your application scales out beyond a single web/app server, it becomes a necessity that the session state must be shared between multiple web/app servers. The common solution is to store session state on altogether different data store and share it with all the Web/App Servers. Though this approach is little complex than in-memory sessions, single point of failure and scalability can be achieved using this architecture pattern. 

Let us explore some popular patterns for web session synchronization on AWS cloud world.


Pattern 1: Synchronization using JGroups




Since AWS Infrastructure currently does not support Multicast protocol, the application layer software should synchronize the session data between them directly using Unicast TCP mechanism. Java based Application servers can use JGroups to synchronize the session data to other Java Web/Application EC2 instances in Unicast TCP of JGroups. This pattern will suffice if there are ~5-10 EC2 Web/App servers in the infrastructure. Also since this pattern follows a distributed approach towards web session synchronization there is no SPOF.  On other hand, If your web application layer has few hundreds of EC2 instances then Unicast TCP will be inefficient because of following reasons; there will lots of sync traffic data among Java Web/App EC2,  EC2 instances will be busy using considerable amount of CPU cycles for synchronization rather than serving web requests and EC2 web/app memory will filled with redundant session data.  
Note : vCider or VPNCubed seemed to support Multicast on AWS. vCider is acquired by Cisco and have stopped new downloads currently. 

Pattern 2: Synchronization using Terracotta Web Sessions




Terracotta(TC) web sessions can be used synchronize the session data in Java based applications. This product comes with client plugin(Terracotta driver) that needs to attached to the Web/App JVM of the EC2 instance and a Terracotta server that can be installed on a separate EC2 instance. The web session data will be optimally* serialized using TCP protocol from the Java Application server to the Centralized Terracotta EC2 server instance.  In case a web request earlier served by App EC2 A reaches App EC2 B because of Round Robin algorithm or App EC2 A failure, the later will check with centralized TC EC2 server instance for the session authenticity and proceed with processing the request without causing problems for the end user. This way the application server can designed to behave stateless and pick up any web requests from any load balancers. In addition to web sessions Terracotta can be extended with their other product lines which can help us store much more information on TC server EC2 instance efficiently. The Terracotta server EC2 instances can also be set HA mode to avoid SPOF in your application. Terracotta also follows an optimized serialization protocol where by only the changed piece of data is sent over the wire and not the entire serialized content. This saves lots of data flowing over the Amazon EC2 NW and proves very handy and effective on scalable deployments.In our experience we found ,Terracotta web sessions are mainly suitable for Java based application servers. It is better to run Terracotta EC2 server instance with High IO SSD EC2 instance type or other larger Memory EC2 instances in AWS cloud because TC EC2 server performs really well when they are given lots of memory and NW leverage. TC server using high memory EC2 instances can use ephemeral with TC HA mode (or) RAID 0+EBS optimized+ PIOPS as underlying storage on AWS for better performance. We have observed this centralized architecture pattern using TC server is suitable for ~20-30 app server farms with heavy traffic in AWS. This is not surely suitable of large web applications running couple of hundreds app servers in their web/app farms. Since the numbers mentioned are primarily dependent upon connections/sec, volume of data and nature of application traffic, I would strongly suggest the teams using this model to do their own benchmarks before concluding.  

Pattern 3: Synchronization using Distributed MemCacheD / Amazon ElastiCache




This is one of the most widely used architecture patterns in the Highly Scalable applications for web session synchronization. Applications written in Java, .Net, PHP, Python etc can use this model to synchronize their sessions. Web Sessions from the Application layer are synchronized(PUT) in the distributed MemcacheD / Amazon ElastiCache nodes using a MemCacheD client(namely spymemcached for Java, respectively for others). Web/App EC2 instances can GET the web session from MemcacheD and authorize them. Though the session data is distributed, the Memcached client has the logic to access and get data from the correct MemcacheD EC2 server. Clients can use TCP,UDP in binary or string format to communicate with MemCacheD Server.
Amazon ElastiCache is an AWS implementation of MemCacheD with better features and control. MemCached can be installed on any Amazon EC2 instance whereas ElastiCache is an Amazon service which exists in a separate tier of your tech stack. It can be accessed thru same memcache protocol over TCP. As best practice Multiple MemcacheD / ElastiCache nodes should be created in multiple AZ's in AWS for storing sessions and other user data. Since the session data is distributed into multiple cache nodes a single MemcacheD node failure will not much impact the user experience. In case session data redundancy is needed you can write(2 or more PUTs) the session data to multiple cache nodes and get from single node. This offers better HA on the distributed cache layer for Cache dependent sites but comes with small latency hick during PUT operation. MemCacheD performs better on High Memory instances with better IO in AWS. Depending upon the Cache Infra architecture we can keep a separate layer of High memory EC2 instances for MemcacheD/ ElastiCache Tier or share the unused space of web/app/other EC2 servers memory using MemCached EC2 installations. Both works well for MemCacheD dependent applications. Since session auth is an important step, TCP with Binary or String mode is recommended for session synchronization in Memcache protocol. We have seen that this architecture can easily handle tens of thousands of concurrent requests/sec in highly scalable applications.

Pattern 4: Synchronization with RDS Master (MySQL,Oracle, SQL)




This is one of the most used architecture patterns in the entry level or some poorly designed applications for web session synchronization. Web Sessions from the Application layer are synchronized in the Centralized Database Master. Though applications written in Java, .Net, PHP, Python etc can use this model to synchronize their sessions, it is not recommended for applications which demands heavy traffic and scalability. The database master will be unnecessarily pounded with Session requests and will be overloaded to perform normal transaction/queries. It is strongly recommended to offload this traffic from the master using other patterns suggested in this article. Example : m1.large RDS MySQL instance type comes with default max connections of 600. If 250 users are going to access your web app then only 350 connections are available for others to perform txns overall. In case your DB is overloaded then you can observe heavy downfall in your txn throughput as well as session authorization requests in this architecture.

Pattern 5: Synchronization with RDS Master+ Multiple Read Replica's




This is an extended version of the pattern 4. The Web Session is created and written in RDS Master and subsequent Session reads are done from the Read Replica slaves. In a web application, session is accessed multiple times during its lifetime and this model offloads that traffic from the RDS Master. One core point to understand in this pattern is; RDS Master asynchronously replicates data to Read Replica Slaves, so in case your DB is heavily pounded with heavy queries/txns there could be a replication lag between Master and Read replica's.  Which means first time when you create a session and immediately try to read it from read slave it may* not be replicated in the slave.This exception has to handled at application code level. This pattern is suggested for applications which are totally designed with DB as the core component and cannot easily migrate to other patterns in short term. On the long term we recommend you to migrate other patterns in AWS.   

Pattern 6: Synchronization with Amazon DynamoDB



Amazon DynamoDB is a NoSQL database that can handle massive concurrent read and writes. You can configure in Amazon DynamoDB console how many read/writes you want per second, accordingly Amazon DynamoDB will provision the required infrastructure at the backend. The infrastructure provisioning operations that happens in the backend are completely abstracted from the end user. The biggest advantage of Amazon DynamoDB is its predictable performance,low latency with seamless scalability. Internally all data items are stored on Solid State Drives (SSDs) and are automatically replicated across three Availability Zones in a Region to provide built-in high availability and data durability. After the launch of DynamoDB, we have architected solutions for some customers using it as a web session data store. It was used for highly scalable applications that need tens of thousands of concurrent requests/sec with persistent session data and specific cache data requirements. Since the web session data are usually in the range of few bytes to KB we were easily able to accommodate this in DynamoDB structure. It is recommended to use "Strong Consistent reads" while transacting with session data in DynamoDB. Amazon DynamoDB also provides APIs and session state extensions for variety of languages like Java,.Net etc. 


Related Articles
Part 1: Understanding Amazon ElastiCache Internals : Connection overhead
Part 2: Understanding Amazon ElastiCache Internals : Elasticity Implication and Solutions
Part 3: Understanding Amazon ElastiCache Internals : Auto Discovery
Part 4: Understanding Amazon ElastiCache Internals : Economics of Choosing Cache Node Type
Launching Amazon ElastiCache in 3 Easy Steps
Caching architectures using Memcached & Amazon ElastiCache
Web Session Synchronization patterns in AWS

Tuesday, February 21, 2012

Configuring Apache Mahout and a Clustering Example

Mahout is an open source machine learning library from Apache. At the moment, it primarily implements recommender engines (collaborative filtering), clustering, and classification algorithms. It’s also scalable across machines. Mahout aims to be the machine learning tool of choice when the collection of data to be processed is very large, perhaps far too large for a single machine.

Several approaches to machine learning are followed to solve problems using Apache Mahout Machine Learning. Supervised and unsupervised learning are the main ones supported by Apache Mahout.

Supervised learning is tasked with learning a function from labeled training data in order to predict the value of any valid input. Common examples of supervised learning include classifying e-mail messages as spam. 
Unsupervised learning is tasked with making sense of data without any examples of what is correct or incorrect. It is most commonly used for clustering similar input into logical groups.

In this post, explanation is given on how to setup Apache Mahout (CDH3 distribution). Its pretty simple to install mahout using CDH3 distribution. If you want to setup apache mahout, follow the instructions in these below steps :
Installation
As mentioned in the overview, Mahout is an open source scalable machine learning library. It is recommended that Mahout runs on top of Hadoop when processing large amounts of data. It is sufficient to install Mahout only on the Hadoop master node.
Before installing Mahout,  ensure that Hadoop is installed in any of the modes. For the purposes of this blog, install Hadoop in cluster mode. Proceed with these commands in the same order -
user1@ubuntu-server:~$ apt-get install maven2
user1@ubuntu-server:~$ cd /opt
user1@ubuntu-server:~$ svn co http://svn.apache.org/repos/asf/mahout/trunk
user1@ubuntu-server:~$ mv trunk mahout_trunk
user1@ubuntu-server:~$ ln -s mahout_trunk/ mahout
user1@ubuntu-server:~$ cd mahout
user1@ubuntu-server:~$ mvn install
P.S.: Sometimes some tests fail while building mahout from source. In such cases use – user1@ubuntu-server:~$ mvn -DskipTests install
Edit .bash_profile to add entry for $MAHOUT_HOME, $HADOOP_CONF_DIR and change $PATH
vim ~/.bash_profile
  • export HADOOP_CONF_DIR=$HADOOP_HOME/conf
  • export MAHOUT_HOME=/opt/mahout
  • export PATH=$PATH:$MAHOUT_HOME
Logout and login for the changes to take effect. After successful login, typing echo $MAHOUT_HOME should print /opt/mahout on the console.
That’s it! Mahout is installed successfully. Lets check it with a Clustering Algorithm sample :
Apache Mahout Clustering Example

Clustering
These techniques attempt to group a large number of things together into clusters that share some similarity. It’s a way to discover hierarchy and order in a large or hard-to-understand data set, and in that way reveal interesting patterns or make the data set easier to comprehend. As an example, Google News groups news articles by topic using clustering techniques, in order to present news grouped by logical story, rather than presenting a raw listing of all articles.
A simple clustering example
This example will demonstrate clustering of control charts which exhibits a time series. A time series of control charts needs to be clustered into their close knit groups. It contains six different classes (Normal, Cyclic, Increasing trend, Decreasing trend, Upward shift, Downward shift). With these trends occurring on the input data set, the Mahout clustering algorithm will cluster the data into their corresponding class buckets.
Follow these steps -
  • If you have not started Hadoop yet, now is the right time.
user1@ubuntu-server:~$ $HADOOP_HOME/bin/start-all.sh
  • Download the input data set
user1@ubuntu-server:~$ wget http://archive.ics.uci.edu/ml/databases/synthetic_control/synthetic_control.data
  •  Copy the downloaded data set into HDFS
user1@ubuntu-server:~$ $HADOOP_HOME/bin/hadoop fs -mkdir testdata
user1@ubuntu-server:~$ $HADOOP_HOME/bin/hadoop fs -put /PATH/TO/synthetic_control.data testdata
(P.S.: HDFS input directory name should be “testdata”)
  • Mahout’s mahout-examples-$MAHOUT_VERSION.job does the actual clustering task and so it needs to be created. (P.S.: if the job file is already present under $MAHOUT_HOME/examples/target/ folder, then skip the following 2 commands.)
user1@ubuntu-server:~$ cd $MAHOUT_HOME
user1@ubuntu-server:~$ mvn clean install
The job will be generated in $MAHOUT_HOME/examples/target/ and it’s name will contain the $MAHOUT_VERSION number.
  • Perform clustering
user1@ubuntu-server:~$ $MAHOUT_HOME/bin/mahout org.apache.mahout.clustering.syntheticcontrol.canopy.Job
user1@ubuntu-server:~$ $MAHOUT_HOME/bin/mahout org.apache.mahout.clustering.syntheticcontrol.kmeans.Job
The clustering output is in SequenceFile format which is not human readable. Hence, we need to use the clusterdump utility provided by Mahout.
  • Copy the cluster output from HDFS onto your local file system
user1@ubuntu-server:~$ $HADOOP_HOME/bin/hadoop fs -get output $MAHOUT_HOME/examples
  • Run clusterdump to convert output into human readable form
user1@ubuntu-server:~$ $MAHOUT_HOME/bin/mahout clusterdump --seqFileDir output/clusters-10 --pointsDir output/clusteredPoints --output $MAHOUT_HOME/examples/output/clusteranalyze.txt
“clusteranalyze.txt” is the human readable output. Go have a look!
Points to remember
  • Make sure that Hadoop is installed successfully and that the daemons are running before running Mahout jobs
  • The HDFS output directory is cleared when a new run starts so the results must be retrieved before a new run
  • Computed clusters are contained in output/clusters-i
  • All result clustered points are placed into output/clusteredPoints


Links:

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