Prefork model

Also known as: prefork

On this page 7

The prefork model is a concurrency design for servers in which a master process creates a pool of child processes in advance, and each child handles one connection at a time. In the field of services & processes, prefork is the classic answer to the question of how a long-running network service serves many clients without starting a new process for every request.

The design became widely known through the Apache HTTP Server prefork MPM, but the same pattern appears in PostgreSQL connection handling, older mail servers, Gunicorn sync workers and many Perl and PHP application servers. Its defining trade-off is simple: strong isolation and simplicity in exchange for higher memory use per connection.

How the prefork model distributes work

A prefork server works by binding the listening socket once in the master and then calling fork() to create children that inherit that socket. Each child blocks in accept(), takes one connection, processes it completely and then returns to waiting for the next one.

The master does not serve requests itself. It supervises the pool, counts idle and busy children, starts new ones when spare capacity falls and terminates surplus ones when traffic drops. Because children are created before demand arrives, the cost of fork() and of loading application code is paid ahead of time instead of on the request path.

Modern kernels make forking cheaper through copy-on-write memory: parent and child share physical pages until one of them writes to a page. Code and read-only data loaded in the master therefore stay shared, while heaps that grow per request become private to each worker process.

The following table shows the main stages in the life of a prefork pool.

StageWhat the master doesWhat the children do
StartupBinds ports, loads configuration, forks initial poolInherit socket, drop privileges, wait in accept()
Steady loadMonitors idle count through a shared scoreboardServe one connection each, then return to accept()
Traffic spikeForks extra children up to the configured ceilingNew children join the accept queue
Quiet periodSignals surplus idle children to exitFinish current work and terminate
RecyclingReplaces children that reached a request limitExit after N requests to release leaked memory
Life cycle of a prefork worker pool

Key parameters that size a prefork pool

Tuning a prefork server means controlling how many processes exist and how long each one lives. The names differ between products, but the same small set of knobs appears almost everywhere.

ParameterApache prefork nameEffectTypical starting value
Initial childrenStartServersPool size at launch5 to 10
Minimum spareMinSpareServersIdle children kept ready for bursts5 to 10
Maximum spareMaxSpareServersIdle ceiling before children are killed10 to 20
Hard ceilingMaxRequestWorkersMaximum simultaneous connectionsRAM divided by per-child size
Recycling limitMaxConnectionsPerChildRequests served before a child exits1,000 to 10,000, or 0 for none
Typical prefork tuning parameters

The most important number is the hard ceiling. It should be derived from memory, not guessed: if each child grows to about 40 to 80 MB with an embedded interpreter and the host can spare 4 GB, the safe ceiling is roughly 50 to 100 children. Setting it higher than memory allows causes swapping, which degrades latency far more than a short accept queue would.

The recycling limit is a defensive setting. It bounds the damage from slow memory leaks in application code by replacing a worker after a fixed number of requests, at the price of an occasional fork and warm-up.

Prefork compared with threaded and event-driven models

Prefork is one of three main concurrency strategies for network servers, and the right choice depends on workload and code safety. Threaded designs place several connections inside one process, while event-driven designs multiplex thousands of sockets in a single loop.

ModelUnit per connectionMemory per connectionFault isolationBest fit
PreforkWhole processHighStrong, a crash kills one childCode that is not thread-safe
Threaded (worker)Thread in a processMediumPartial, a crash kills all threadsThread-safe modules, moderate load
Event-drivenCallback or coroutineLowWeak, one bug can stall the loopMany idle or long-lived connections
Hybrid (event MPM)Threads plus event loopLow to mediumPartialKeep-alive heavy web traffic
Concurrency models for network services

The practical difference shows up with slow or idle clients. A prefork child stays occupied for the whole keep-alive period, so a few hundred idle connections can exhaust the pool, whereas an event loop holds the same sockets for a few kilobytes each. This is why reverse proxies such as nginx are commonly placed in front of prefork back ends to absorb slow clients.

Where the prefork model is still the right choice

Prefork remains appropriate wherever process isolation matters more than density. The clearest case is application code or libraries that are not thread-safe, such as older PHP extensions loaded through mod_php or C modules with global state.

  • Untrusted or fragile code: a segmentation fault ends one request, not the whole service.
  • Per-process privileges: each child can run with its own credentials or resource limits.
  • CPU-bound work: separate processes use all cores without contention for an interpreter lock.
  • Simple debugging: one request per process makes tracing and profiling straightforward.

Typical deployments therefore combine prefork with a graceful restart procedure, in which the master replaces children one at a time after a configuration change, and with a process supervisor that restarts the master itself if it fails.

Limitations and common mistakes with prefork servers

The main limitation of the prefork model is linear memory growth with concurrency. Every simultaneous client needs a full process, so the model scales poorly to thousands of concurrent connections and wastes resources on idle keep-alive sessions.

The table below lists frequent operational problems and their usual remedies.

SymptomLikely causeFix
Host starts swappingCeiling too high for per-child sizeRecalculate the ceiling from measured memory
Requests queue at peakPool exhausted by keep-alive clientsShorten keep-alive or add a reverse proxy
Memory creeps up for daysLeaks in application codeSet a recycling limit on each child
Latency spikes after idle timeToo few spare childrenRaise the minimum spare value
Thundering herd on acceptAll idle children wake for one connectionUse accept serialization or SO_REUSEPORT
Prefork symptoms, causes and fixes

A frequent misconception is that prefork is obsolete. It is less efficient per connection, but on hosts with ample memory and moderate traffic it remains predictable, robust and easy to reason about, which many operators value above raw throughput.

In simple terms

Imagine a bank that hires a fixed team of tellers before the doors open. Each teller serves one customer at a time, and the manager watches the queue, calling in extra tellers when it grows and sending some home when it shrinks.

The prefork model works the same way inside a server. The tellers are separate processes, prepared in advance so nobody waits for one to be hired. If one teller makes a mistake and has to leave, the others keep working. The cost is that every teller needs a desk, so more customers at once means more memory.

A practical example

A small hosting provider runs a legacy PHP application on Apache with mod_php on a virtual machine with 8 GB of RAM. Some PHP extensions in the stack are not thread-safe, so the team keeps the prefork MPM instead of switching to threaded workers.

Measurements show that each child grows to about 60 MB under real traffic. The administrator reserves 2 GB for the operating system and database cache and sets MaxRequestWorkers to 100, with 10 minimum and 20 maximum spare children and a recycling limit of 5,000 requests to contain a known memory leak.

To stop idle browsers from tying up children, nginx is placed in front as a reverse proxy that buffers slow clients and keeps short keep-alive times to the back end. The result is stable memory use under peak load, no swapping, and isolated crashes that affect only a single request.