Login

minimal nginx conf to split get/post requests

Author:
amitu
Posted:
October 14, 2008
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# inspired by http://weichhold.com/2008/09/12/django-nginx-memcached-the-dynamic-trio/
# /etc/nginx/sites-enabled/default
upstream backend_get {
        server 127.0.0.1:8080 weight=1; 
        # any number of servers can be added here to distribute load. 
}

upstream backend_post {
        server 127.0.0.1:8081 weight=1; 
}

server {
        listen   80;
        server_name  localhost;

        access_log  /var/log/nginx/localhost.access.log;

        location / {
                proxy_read_timeout 300;
                if ($request_method = POST)
                {
                        proxy_pass http://backend_post;
                        break;
                }
                # update: after http://simonwillison.net/2008/Oct/14/django/
                # use master while the cookie lasts 
                if ($http_cookie ~* "force_master=([^;]+)(?:;|$)")
                {
                        proxy_pass http://backend_post;
                        break;
                }
                proxy_pass http://backend_get;
        }
}


# PostCookieMiddleware
class PostCookieMiddleware(object):
    """ cookie force_master to take care of replication lag """
    def process_response(self, request, response):
        if request.method == "POST":
            # for next 10 seconds send all requests for this user to master
            response.set_cookie("force_master", "42", max_age=10)
        return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.