Why nginx is faster than Apache

After doing considerable research over the Internet I found following as the major Advantages of using nginx vs using Apache.

Apache
1) Apache uses a blocking model of using threads for processing requests.
2) One thread is dedicated for serving one request.
3) The threads have to do sync with there Process so it’s a synchonous event.
4) Apache has to allocate ~1 MB per process just to start with, apache has to create process by cloning itself, consider apache with php, that itself is around 20 MB, now if apache starts 5 processes, memory footprint becomes 100 MB.
5) It’s basically useless to use threaded model on old CPUs (uni-threded).

nginx
1) nginx is a event based web server.
2) It uses (it’s own implementation of ) libevent and Reactor Pattern to process requests.
3) Event model is non-blocking and asynchronous.
4) nginx recives requests, transfers it to the system for processing without blocking the resources and listens to events using “kqueue, epoll/select” etc, when the data/document is processed and ready to be served, the request handler serves it back to the client.

After above research, it’ll be injustice if I do not give some credit to the Process vs Thread show.

Threads vs Processes

1) Processes need to be “forked” or “cloned” from Parent process, they are exact copy of parent to start with while threads are subset of a Process, it’s often termed as a “lightweight process”.
2) Processes have their own execution environment, memory space, kernel space and user space which threads share while execution.
3) Processes need to use Inter Process Communication for talking to other Processes which threads can talk to other threads within the same process directly and hence faster.
4) Threads run in same context as of their Parent Process, while a Process can alter the resources and contexts in the run-time of a program.

I stole many thoughts from here, here and here.

Subscribe
Notify of

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
11 years ago

“It uses libevent”
Wrong. Nginx doesn’t use libevent. It has its own implementation.

9 years ago

Thread creation is not necessarily much faster than process creation. When a process is forked, the child only gets a copy of the page table of the parent and not the whole memory. When either process changes a page, a copy of the page is created for the child process. This is known as “Copy on write”, Apache by default uses process pools not threads (at least on unix based systems).