Load Testing - Node.js vs Single Threaded Python Web Server vs PHP5+Apache2.2

Load testing is generally used to test performance of any product by putting it under extreme conditions and one can know about expected performance in worst scenario. In case of web applications, this is acheived by with writing a bot script or using some automated tools like Seleneium.

So, I got curious about testing the relative performace of a webserver written in Node.js, a single threaded Python web server and one application written in PHP and hosted on Apache 2.2 web server. Task of web application was to get exactly 5 key-value pairs via GET request and insert it into MongoDB database. For example - if one url like http://127.0.0.1:8000/?key_1=value1&key_2=value2&key_3=value_3&key_4=value_4&key_5=value_5 is called, then one document like {key_1:value_1, key_2:value_2, key_3:value_3, key_4:value_4, key_5:value_5} will be inserted in the existing collection of some MongoDB database.

For this testing I wrote a Python script which works something like this -

  1. A set of urls arerequested parallely to web server inside the python test script.
  2. It waits for response for each url until time out limit is reached.
  3. If there is any URLError like "connection timed out" or any HTTPError, we count all of them
  4. Above 3 steps are repeated in a for loop say for a given no. of times.
  5. Above 4 steps are repeated by varying count of urls in the set for parallel request.

Results

Click here to see the image in new window.

Screenshot of results

Analysis

As you can see in the screenshot that

  1. node.js is vey quick in handling requests even if only instance of node is running. This is because of intelligent architecture of node and event based handling.
  2. PHP5+Apache 2.2 is not as fast as node but performance is acceptable. In apache, many child processes are created under one parent process which leads to good performance.
  3. In case of single threaded Python server, requests are handled after one another. Due to this as no. of parallel requests increases we get very bad performance and lot of requests face "Conncetion timed out" error.

This means, web applications written in node.js can handle very large no. of requests at a time (as they one node instance can handle as many as 10000 requests at a time), PHP5+Apache can be a good option if you are not expecting very high traffic on you website. On the other hand, single threaded Python servers should never be used in production systems but they help a lot in while developing any web application using Python based frameworks like Django, Web2py or Pylons.

Thanks for reading till last line, please leave a comment.


run.py

#! /usr/bin/env python
import random
import urllib
import urllib2
import string
import datetime
import time
from threading import Thread, enumerate

URIS_COUNT = 500 #total no. of urls to be accessed in parallel
FORLOOP_COUNT = 100 #total no. of loops in which prallel request will be sent
TIME_OUT = 5.0 #timeout in seconds
UPDATE_INTERVAL = 0.01 #update interval for checking threads
BASE_URL = 'http://127.0.0.1:8000/' #base url of server, remember trailing slash is required

errors = {} #this dictionary is used to store count of all sort of HTTPError and URLError

def rand():
    return ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20))

def dict_to_query_string(d):
    return '&'.join([k+'='+urllib.quote(str(v)) for (k,v) in d.items()])

class URLThread(Thread):
    def __init__(self,url):
        super(URLThread, self).__init__()
        self.url = url
        self.response = None

    def run(self):
        req = urllib2.Request(self.url)
        try:
            self.request = urllib2.urlopen(req)
            #self.response = self.request.read()
        except urllib2.HTTPError, e:
            try:
                errors['HTTPError Code - '+str(e.code)] += 1
            except KeyError:
                errors['HTTPError Code - '+str(e.code)] = 1
        except urllib2.URLError, e:
            try:
                errors['URLError Reason - '+str(e.reason)] += 1
            except KeyError:
                errors['URLError Reason - '+str(e.reason)] = 1
        else:
            pass


uris = []
for k in range(URIS_COUNT):
    values = {}
    for j in range(5):
        values[rand()]= rand()
    uris.append(BASE_URL+'?'+dict_to_query_string(values))


def multi_get(uris,timeout=TIME_OUT):
    def alive_count(lst):
        alive = map(lambda x : 1 if x.isAlive() else 0, lst)
        return reduce(lambda a,b : a + b, alive)
    threads = [ URLThread(url) for url in uris ]
    for thread in threads:
        thread.start()
    while alive_count(threads) > 0 and timeout > 0.0:
        timeout = timeout - UPDATE_INTERVAL
        time.sleep(UPDATE_INTERVAL)
    return
    #return [ (x.url, x.response) for x in threads ]


start_time = datetime.datetime.now()
for i in range(FORLOOP_COUNT):
    print 'Step no. - %d'%(i+1)
    multi_get(uris,timeout=100.0)
end_time = datetime.datetime.now()

td = end_time - start_time
seconds = td.days*24*3600 + td.seconds + float(td.microseconds/10**6)

print '**********************Finished********************'
print 'Total time taken = %f seconds'%seconds
print errors
print '**************************************************'

example.py

#! /usr/bin/env python
import datetime
import sys
import BaseHTTPServer
from urlparse import urlparse
from pymongo import Connection

connection = Connection('localhost', 27017)
db = connection.mydb
collection = db.mycollection

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(s):
        s.send_response(200)
        s.send_header('Content-type', 'text/plain')
        s.end_headers()
    def do_GET(s):
        s.do_HEAD()
        qs = urlparse(s.path).query
        params = dict([part.split('=') for part in qs.split('&')])

        if not len(params)==5:
            print 'Query string should have exactly 5 key value pairs.'
            s.wfile.write('Failure')
        else:
            print 'Query String has been saved successfully'
            collection.insert(params)
            s.wfile.write('Success')

server_class = BaseHTTPServer.HTTPServer
handler_class = MyHandler
server_address = ('', 8000)

httpd = server_class(server_address, handler_class)

print 'Server Starts'
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
print 'Server Stops'

example.js

var http = require('http');
var url = require('url');
var mongo = require('mongodb')
db = new mongo.Db('mydb', new mongo.Server('localhost', 27017, {}), {});

db.open(function() {
    db.collection('mycollection', function(err, collection){
        http.createServer(function (request, response) {
            var query = url.parse(request.url, true)['query']
            var count = 0;
        for (var key in query){
            count += 1;
        }

        response.writeHead(200, {'Content-Type': 'text/plain'});

        if (count>5 || count<5){
            console.log('Query string should have exactly 5 key value pairs.')
            response.end('Failure');
        }else {
            collection.insert(query, function(){
                console.log('Query String has been saved successfully.');
            });
            response.end('Success');
        };
        }).listen(8000);
    });

});

console.log('Server running at http://127.0.0.1:8000/');

example.php

<?php
try {
    $m = new Mongo('localhost:27017', array('persist'=>'x')); //creating new mongo connection.
    $db = $m->selectDB('mydb');
} catch (MongoConnectionException $e) {
    echo '<p>Couldn\'t connect to mongodb, is the "mongod" process running?</p>';
    exit();
}

$collection = $db->selectCollection('mycollection');

$query = $_GET;

if (count($query)==5){
    $collection->insert($query);
    echo 'Success';
} else {
    echo 'Failure - Query string should have exactly 5 key-value pairs.';
    exit();
}
?>

Need for Sustainability in Agricultural Practices and Food Production in India

What is Sustainability?

According to FAO(Food and Agriculture Organization) definition of sustainable agriculture development is "the management and conservation of the natural resource base, and the orientation of technological and industrial in such a manner as to ensure the attainment and continued satisfaction of human needs for present and future generations. Such developement conserves land, water, plant and animal genetic resources, is environmentlly non-degrading, technically appropriate, economically viable and socially acceptable".

Present scenario

  1. Demand for Food Production - Despite of many advancements in Agricultural and Food Engineering million people are undernurished every year in our country and malnutrition accounts for nearly 50% child deaths. Food production needs to get doubled by 2025 as it was in 1995 so that population can be fed adequately. But this parallel demand of food production with population growth will result in pollution, and degradation of natural resource, again which limits sustainable development.
  2. Wastage of Agricultural Items - Around Rs. 500 billion worth of agricultural items get wasted every year in India. Generally wastage of food items occurs at various stages of handling after harvesting due to fragmented farming, lack of post-harvest infrastructure such as cold chain facilities, transportation and proper storage facilities etc.
  3. Declining ground water - There has been decline in groundwater level by 5-10 meters in recent past. Possible reasons for these are increased number of tubewells and destruction of indigenous systems for storing runoff water, which are essential because rainy days are very few and erratic. Due to all this when rainy season is over, there is no retainment of rainy water in catchments and farmers as well agriculture production suffers.

Critical issues with Indian Agriculture

  1. Knowledge deficit and infrastructure deficit in rural areas
  2. Problems related to irrigation infrastructure, market infrastructure and transport infrastructure
  3. There are number of schemes for developing agriculture but these are ineffective due to lack of proper delivery mechanisms that can translate these scemes into effective facilitation at ground level in terms of increasing productivity, decreasing cost or increasing price realization.
  4. Agriculture is subjected to high risks because of volatile nature of factors involved. Therefore Governement should provide supports to farmers.
  5. Unequal distribution of irrigation facilities to farmers across country.

How to achieve Sustainable Agricultural Development

We need to use new approaches to increase food production while protecting the natural resources. For example -

  1. fully exploit natural processes such as recycling nutrients, using plants that fix their own nitrogen and achieving a balance between pests and predators
  2. reduce the reliance on inputs such as mineral fertilizers and chemical pesticides
  3. diversify farming systems, making greater use of the biological and genetic potential of plant and animal species
  4. improve the management of natural resources
  5. rotate crops or develop agroforestry systems that help maintain soil fertility.

Among other practices, Indian Agriculture really needs following things -

  1. Water Harvesting - As all of us know that water is the most important natural resource and national asset. But in India, water availability per capita is on decline as rivers are drying up, ground water is depleting, canals are polluted and massive urbanisation. It's funny but the only place in town with constant running water is gutter. Even if our country is having fair amount of annual rainfal, over 80% of water recieved from rainfall is lost as runoff. Sufficient no. of check dams should be made so that enough percolation of water may occur. Thsi will ensure rise in underground water level and increased water availability for all. Food and beverages will need to reduce use of gorund water and adopt rain water harvesting like Bisleri did. This practice of rain water harvesting is being used in many parts of country in different projects but momentum needs to be increased.

  2. Organic Farming - Organic farming methods are not new for we indians. In the hurry of modernization of agriculture we have been losing traditional methods of farming very fast. Pracices used by previous generations are lost now, and farmers have to spend large sum of money on chemical fertilizers and pesticides etc. Need for pursuing organic agriculture is because we need to feed this increasing population but at the same time production should be increased in sustainable manner. People have realized that "Green Revolution" with high input has reached a plateau and is now sustained with diminishing return of falling dividends. Chemical fertilizers are produced from fossil fuels and as it's diminishing in availability, we can't coninue with concept of Intensive Farming because it will be costly in near future. On the other end, organic agriculture is enivitonmental friendly, health hazards will be reduced, soil health will improve and natural resources are used in optimized manner. Organic farming is being followed nowadays but it appears to be costly than intensive farming due to small scale production. But momentum in adoption of organic farming really needs to increase to achieve sustainabilty in short time.

  3. Micro Irrigation - As all of us know that lot water is used in cultivating different crops and most of this requirement is fulfilled by trivial irrigation methods. But this involves much higher use of water than actual requirement of crop. Micro irrigation practices reduce this difference by large extent. Besides this micro-irrigation helps in improving micro climate and overall production is increased. Therefore, indian farmers should adopt this kind of practices for efficient use of water and increased production.

New approaches for being Sustainable

New concepts like Carbon Emission Trading, Water Footprinting etc. are coming up to control climate change and save the natural resources. Social initiatives like Fair Trading etc are motivating people towards sustainable agriculture. Let's hope these things will have good impact in India as well in near future.

Thanks for reading this post, let's try to achieve sustainable development in each industry so that upcoming generations have something good to talk about us. Please leave a comment

Prikriti’11 - Agri and Food Innovation Fest

Posted on 16 Mar, 2011 Tags prakriti agri Comments

Initiation

Idea for organizing Prakriti came to some of our seniors in 2009 after seeing kind of frustration in students of our department when they were not getting good jobs, good internships etc. in this field. Some reasons were like unawareness between students regarding scope of this field and kind of weak bonding between Agricultural and Food Indutries and our department. Everyone was saying “Curricula Change Karao Ghasi Ka, Ye Sab Padh Ke Job Nahin Lagne Waali”. But one can not change a well established system just by organizing a panel discussion or some fest. Anyway, we started contacting our alumnus, different comapnies and colleges to take part and finally Prakriti’10 happened from 2nd to 4th April, 2010. Response was good both from our Professers, Industry and participating colleges and everyone asked us to move forward with Prakriti’11.

Why I wanted to be part of Prakriti and how it helped me

I developed a “KEEDA” inside me for working on computers in my 1st and 2nd years and had feeling for contributing to Prakriti’10 website. But when I joined Team Prakriti’10, website was already up and seniors asked me to do some designing related works using Photoshop.
Personally, I earned lot of things during Prakriti’10, one of them was interaction with lot of departmental seniors and got to know "What to do and what not to do when you are a Ghasi. One of them was “Apni CV Ghasi se Jitna Door Rakhoge Utna Hi PEACE Rahega Life Mein”. It sounds kind of absurd after having Prakriti’11 but this was the funda given to me at that point of time.

Finally, I got back to programming due to this funda and learned Django Framework of Python during summer holidays. This helped me in being part of Overnite, an online coding contest organized during tech fest of IIT Kharagpur. I got a chance to work with Mr. Varun Kumar, an agfe senior, during last winters and developed Prakriti’11 website as well. Finally, I got to know lot of good coders in IIT Kharagpur after this.

Why we went for Prakriti’11

As I said prevously, a platform was missing where students in this field could interact with Industry people. Many companies are not aware of the fact that there is one AgFE Department in IIT Kharagpur and why they should take us in Food Industry instead of Chemical Engineers, in Land and Water Resources related Industry instead of Civil Engineers and in Tractor Industry instead of Mechanical Engineers. Why are we better than all of them as far as our particular field is concerned. Generally, all of us from this field find other jobs like IT and Finance more fascinating than working for a tractor or food company. One of the reasons was wrong interpretation of being a Ghasi and we wanted to change this interpretation by both companies and students.

What happened during Prakriti’11 and how was response

Prakriti’11 happened from 11th to 13th March, 2011 and we had around 100 participants from different agricultural engineering colleges across the country. Many events, workshops were organized during these 3 days - - Symposium - an interaction between industry and acadmia - Agripreneurship Workshop - Tech Villa - workshops on automation, tea and IT in agriculture - Innovation Workshop by John Deere - Sustainability Workshop by Tetrapak - Vantage - an innovative fun event - Quiz

I think, Prakriti’11 helped participants to get an insight about what’s there in blackbox of companies in Agricultural and Food industries and what can they do there.
This time in Prakriti we tried for some online events like Online Quiz and Online Video submission on Sustainability. Online Quiz saw much more than expected traffic in first 3–4 four days due to which we needed to upgrade our hosting plan because bandwidth use was going to be a problem and no one was in mood to stop the fever. This fever continued for 10 continuous days and we saw more than 20,000 attempts for answerng different question by more than 200 players. The addiction factor behind this simple application was Countdown Timer. This timer which was responsible for linear decay in maximum marks after a soft time limit. Same thing happened with Online Video submissions and we had total 8 submissions on were Facebok page which lead to more than 2500 likes in 15 days.

Plan for Prakriti’12

Everyone is excited to have Prakriti’12 and we are getting very much positive response from participants and our professors. Let’s see what happens !!!

External Links

Previous Page: 1 of 1 Next