Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 30 ยท First Steps

Nginx vs Apache: Architecture and Choosing

Compare Nginx and Apache: event-driven workers vs prefork, worker and event MPMs, memory per connection, modules, .htaccess trade-offs and when to use both.

Nginx and Apache both do the job from the last lesson, and either can serve a small site equally well. They differ in how they organize the work inside, and that difference decides how they behave when thousands of visitors connect at once, how they are extended and how much control you hand to the people who deploy sites. Knowing those differences lets you choose with reasons instead of habit, and it makes the configuration you will learn later easier to understand.

This lesson is conceptual, so the only code is a pair of small JavaScript simulations. They are models with round, made-up numbers: they show the shape of the behavior (how limits and waiting scale) and not benchmark results of the real software.

Two ways to handle many connections

Imagine a restaurant. In the first design, each customer gets a dedicated waiter who stands at the table the whole meal, even while the customer reads the menu or chats. In the second design, a few waiters circulate and serve whichever table needs something right now. The first needs many waiters but is simple to reason about. The second needs very few but is more complex to build.

That is the core split:

  • Process or thread per connection. A worker takes a connection and stays attached to it until it closes. While the client is slow, thinking or just keeping the connection open, the worker sits idle but unavailable.
  • Event-driven. A small number of workers each run a loop that watches thousands of sockets. When a socket becomes ready (data arrived, buffer drained), the loop does a little work for it and moves on. Waiting costs almost nothing.

Nginx was designed event-driven from the start. Apache grew up process-based and later added more efficient models.

Nginx: master and workers

Nginx runs one master process that reads the configuration and manages several worker processes (worker_processes auto; sets one per CPU core). Each worker is single-threaded and handles thousands of connections with an event loop on the operating system's readiness API (epoll on Linux). Because a connection is only a small structure in memory, an idle keep-alive connection costs on the order of kilobytes, not megabytes.

NGINX
worker_processes auto;

events {
    worker_connections 4096;   # per worker
}

The price of this design: a worker must never block. Anything slow, like running application code inside the worker, would stall every connection it handles. That is why Nginx forwards dynamic work to other programs (PHP-FPM, Node, Python servers) and does not run application code inside itself. You will see this in PHP, FastCGI and Application Servers.

Apache: MPMs

Apache separates its core from the way it handles connections, which is chosen by an MPM (multi-processing module). You pick exactly one:

Apache's three MPMs

prefork One single-threaded process per connection.
worker Several processes, each with many threads.
event Like worker, but idle keep-alive is handled apart.

The event MPM is the usual default on modern distributions.

1 / 2

prefork keeps a pool of processes, each handling one connection at a time with no threads. It is robust and compatible with anything, including libraries that are not thread-safe, but every connection costs a whole process worth of memory. worker runs several processes, each with many threads, so one connection costs a thread. event improves on worker: a separate listener thread watches idle keep-alive connections, so a connection that is just waiting does not pin a worker thread. With the event MPM, Apache comes close to the event-driven model for idle connections, though it is still thread-based for active ones.

Which MPM your server uses depends on the distribution package and on the modules you enable. Classic mod_php forced prefork on many servers, which is a large part of Apache's old reputation for being heavy. Running PHP through PHP-FPM lets Apache use the event MPM.

APACHE
# Which MPM is loaded? (read-only; apachectl -V also shows it)
LoadModule mpm_event_module modules/mod_mpm_event.so

<IfModule mpm_event_module>
    ServerLimit              4
    ThreadsPerChild         25
    MaxRequestWorkers      100
</IfModule>

MaxRequestWorkers is the ceiling on simultaneous connections that are actively being served. When all of them are busy, new clients wait in the listen queue. Our first simulation makes that visible.

Simulation 1: many idle connections

Suppose 2,000 visitors open a connection and keep it open, idle, for a while (a common situation with keep-alive, long polling or slow mobile clients). How much memory does each model need, and how many of them get served at all? The numbers below are invented but round, so you can follow the arithmetic:

JS Process per connection vs event loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first model hits its worker limit at 150 and leaves 1,850 clients waiting, while spending about 1.5 GB on workers that are mostly idle. The second holds all 2,000 in about 48 MB, most of it the base memory of four worker processes. Raising the limit in the first model costs more memory; lowering it makes more clients wait. That trade-off is what MPM tuning is about. Real numbers vary with modules, TLS and application code, so always measure your own setup.

Simulation 2: slow clients

Idle connections are one problem. Slow ones are another: a client uploading over a bad network can hold a connection for a long time while doing almost no work. The simulation below has four slow clients arrive at time 0 and each holds its connection for 1,000 time units. Then ten fast requests arrive, each needing 5 units of work. The process model has 4 workers, and the event model uses one loop whose CPU is only busy while it actually works.

JS Four slow clients and ten fast requests

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The fast requests wait almost the entire 1,000 units behind the slow clients in the first model and finish promptly in the second. This is the so-called slow-client problem, and it is also why even an Apache site is often fronted by Nginx, which absorbs slow clients cheaply (more on that in Nginx in Front of Apache). Apache's event MPM narrows the gap for idle keep-alive connections, but a client in the middle of a slow request can still occupy a worker thread.

Modules

Both servers are modular, but they load modules differently.

  • Apache loads modules at startup with LoadModule, can enable or disable them without recompiling (a2enmod on Debian), and has a very large ecosystem: mod_rewrite, mod_ssl, mod_proxy, mod_security, authentication modules and many more.
  • Nginx modules were historically compiled in at build time. Since version 1.9.11 many can be dynamic modules loaded with load_module, but a dynamic module must be built for the exact Nginx version. The distribution packages ship the common ones.

.htaccess: freedom and its cost

Apache can read a file named .htaccess inside any directory, and apply its directives to that directory and below, with no reload. That made shared hosting practical: a customer can control redirects and access rules without touching the main configuration. Many applications ship with an .htaccess file for their rewrite rules.

The cost is performance and clarity. For every request, Apache checks every directory along the path for an .htaccess file, and your rules can be spread across many files. Nginx has no equivalent: all configuration lives in the main files and changes need a reload by someone with server access. That is less convenient for tenants and cheaper and more predictable for operators. You will study the Apache side in .htaccess, Directory Rules and AllowOverride.

How to choose

Question Leans toward
Mostly static files, reverse proxy, load balancer, TLS front end Nginx
Huge numbers of idle or slow connections Nginx
Shared hosting, per-directory rules, .htaccess-driven apps Apache
Need an Apache-only module or mod_rewrite conventions Apache
Team already knows one and the load is modest The one you know
Slow clients and complex app rules together Nginx in front of Apache

Many production sites use both: Nginx on ports 80 and 443 handling TLS, static files and slow clients, and Apache on a loopback port running the application with its .htaccess rules. Neither choice is wrong. Pick by the workload, the modules you need and what your team can operate well.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does an event-driven server handle many idle connections cheaply?

    A worker's loop watches many sockets and only works on those that are ready, so waiting connections cost a few kilobytes each.
  2. 2. Which Apache MPM is the usual default on modern distributions and handles idle keep-alive connections separately?

    The event MPM adds a listener thread for idle keep-alive connections, so waiting clients do not hold worker threads.
  3. 3. Why did classic mod_php often force Apache to use prefork?

    Non-thread-safe libraries inside mod_php made threaded MPMs risky. PHP-FPM removes that coupling.
  4. 4. What is a common downside of .htaccess files?

    Looking for and parsing .htaccess in every directory of the path costs time on every request, and rules end up scattered.
  5. 5. A site has slow mobile clients and an application that depends on Apache-only .htaccess rules. What is a sensible design?

    Nginx absorbs slow connections cheaply and Apache keeps its rules and modules, which combines the strengths of both.

Summary

  • Nginx is event-driven: a master process plus a few single-threaded workers, each watching thousands of sockets, so idle connections are very cheap.
  • Apache chooses an MPM: prefork (process per connection), worker (threads) or event (threads plus a separate handler for idle keep-alive).
  • Never block an event loop: Nginx hands application code to other programs such as PHP-FPM.
  • Apache modules load at runtime with LoadModule; Nginx modules are compiled in or loaded as version-matched dynamic modules.
  • .htaccess gives per-directory control without reloads but costs a lookup per request; Nginx has no equivalent.
  • Choose by workload and team skills, and remember that combining them is common.

Next: Nginx Configuration Syntax