nginx memory management algorithm?

Vladimir Shebordaev vshebordaev at
Sat Jun 30 04:32:04 UTC 2012


2012/6/30 naquad <naquad at>:
> I'm trying to figure out how does nginx manage its memory per request. From
> what I understand it uses region-based memory management (implemented in
> src/core/ngx_palloc.{h,c}).
> But is there any documentation on details of its implementation and
> algorithm itself?

Basically, the pool memory allocator in nginx is not that complicated,
so I guess there is no dedicated document.

> I've tried to just read through sources, but I can't get figure algorithm
> out of them :(
> Could somebody please sched some light on this?

As per core/ngx_palloc.h, the pool is nothing but a list of memory
chunks named as blocks described by embedded ngx_pool_data_t .

Regular allocations get the memory from the current chunk.

When the requested amount of memory does fit neither into current
chunk nor into other partially full chunks but still has a modest size
- the one specified at pool creation time either the system page size,
whichever is smaller, -  new memory block is requested from the
system, put on the list of chunks and installed as the current chunk
for regular allocations.

When the amount of memory is requested that is larger than p->max,
i.e. the one specified at pool creation time either the system page
size, whichever is smaller, it is allocated directly from the system
with ngx_alloc and put on p->large list.

Please notice, the pool allocator in nginx is specifically designed
for speed and efficiency, it doesn't store the information about
particular allocations neither allocated objects bear such
information. So, the only mean to reclaim memory is to destroy the

When you allocate from  pool the objects having accotiated system
resources that are to be released along with the object itself, e.g.
file buffers, you can install a cleanup handler that is to be invoked
at pool destruction time.

> Thank you.

In the hope it helps.


More information about the nginx-devel mailing list