Reserve First Memory Strategy/Example for Memory-Management-Dummies

Hey there,

at the moment I tinker with memory management; in general and of course for my personal projects.

I read a lot about that reserving first is a popular and regularly used approach for some Zig programs (though, not for all).

While I use Zig now for over a year, I’m not very used to memory management. For my stuff I mostly manage memory the “standard” way: allocate when and where required through explicit calls to alloc, dupe, std.mem.whatever.... While that of course works good enough for now, I want to enhance my workflows. For now I already started using ensure/init/assumeCapacity stuff for array etc. (while its not exactly the same as general mem management).

However, I would like to understand better how the general most “extreme” version of reserving anything up front works. I read several articles/threads[1][2][3][4] and tried looking into Tigerbeetles codebase. While the latter is a little bit above my understanding level, I also couldn’t figure out so far how to accomplish that reserve-first approach in a practical sense.

Thus, I would be happy for some insights by all the memory management pros around here. Particular how to reserve first and thereafter use this reserved memory pool for actions/functions/methods that need allocations. Can be a dead simple example; think of me as kind of blockhead regarding this topic :wood: :smile:

Already thanks in advance to anybody taking there time bothering with this question!


  1. Reserve First ↩︎

  2. Initial ArenaAllocator node capacity ↩︎

  3. Reserve First - #4 by andrewrk ↩︎

  4. Memory pools and reused arenas vs fast GPA ↩︎

So, in the past, you had std.BoundedArray, which I never used myself but heard people talk about.
It’s a simple and straightforward example of the “reserve first” approach.
It has an ArrayList() like API surface, and you call it like ArrayList(), but with an extra array length parameter. (E.g. BoundedArray(u32, 1024))
It is, quite literally, an array of that length with an additional slice-length field.
If you try to append something to the BoundedArray() such that its length field would exceed the length of the array, it returns error.Overflow.

Since it truly is just an array extended with methods, it never once needs to use std.mem.Allocator. The array can be passed around on the stack, or embedded in the executable so that the operating system allocates it for you on program startup and frees it for you on program exit.

If you wanted a container similar BoundedArray you could use a FixedBufferAllocator which may be more useful as it has an allocator interface.

Obviously it matters on a case-by-case basis, generally if you do find yourself writing stray alloc, dupe, and appends see if you can deduce the total number of elements before appending; some times you can’t, or maybe it will require restructuring data/file formats. When saving data in some of my programs I like to use a simple line-by-line format, each data point is readable but shouldn’t really be editing by hand. I could just store it line by line and read it line by line with a reader’s takeDelimiter('\n') and allocate for each data point on the line. Or I could change the format to store the total first, then each element line-by-line. This change lets me pre-allocate the appropriate buffer before reading, and without reading ahead then going back.

As another example HTTP 1 headers could be infinite, and a client does not specify how many headers are going to be sent ahead of time. You cannot pre-allocate for these headers, nor seek ahead, but you could set an upper limit of bytes. On the flip side HTTP 1 usually include a “Content-Length” header which lets you pre-allocate or reject request bodies of a given size.

I wouldn’t take “Reserve First” as dogma, but an easy optimization to take when applicable that the compiler cannot do automatically.

(Obligatory preface: it doesn’t matter what folks on the Internet say, do what makes sense for your use-case)

There are two somewhat related, but very different ideas here: what I call Reserve First, and what we at TigerBeetle call Static Memory Allocation, but which is perhaps better understood under its original catchy moniker of “no dynamic memory allocation after startup”.

Reserve First is a local (a single function body), positive advice: if you need to add an item to two array lists, don’t write code like

try xs.append(gpa, item);
try ys.append(gpa, item);

instead, write something like

try xs.ensureUnusedCapacity(gpa, 1);
try ys.ensureUnusedCapacity(gpa, 1);

xs.appendAssumingCapacity(item);
ys.appendAssumingCapacity(item);

The latter pattern deals much better with partial failure: if only some allocations succeed, you still end up in logically consistent situation. Eg, if there’s an invariant that xs and ys have the same length, you don’t need to worry that one would be longer than the other if the second allocation fails.

The magic here is that reservation operations acquire physical resources, but don’t change logical state of the program, are idempotent, and make subsequent operations infallible.

This rule-of-thumb you can apply pretty mechanically in any function that takes a gpa as an argument.

Static Memory Allocation is a different beast. It’s a global (whole program), negative advice: just never allocate after startup at all. Don’t minimize the amount of allocs after startup allocation, make it the exactly zero.

Unlike Reserve First, this is not a sprinkle of magic dust you can add anywhere to your program to taste. This generally requires ground-up design of the application/library around the idea of known, explicit, static limits for everything. You do a data-oriented analysis of the problem you are solving, and then you change the definition of the problem such that the solution allows for static allocation.

E.g, TigerBeetle is a database, where the bulk of data are bytes on disk. The data gets into and out of a database via network request. It doesn’t make sense to make network requests arbitrarily large, as that increases latency, and makes it more likely that a request fails. Therefore, there could be a physical size limit on how large a single request could be. For TigerBeetle, that is 1MiB.

Now, if you always add to your ocean of data by 1MiB data drop at a time, you could actually design the whole thing such that you need only O(1MiB) extra memory. If you manage to limit the input, the output/intermediate state is usually limited, even if discovering the limits takes a lot of effort. Eg. because we know the input is 1MiB, and we know that one financial transfer is 128 bytes, that means we are doing at most 8K transfers at a time. Each transfer touches two accounts, so it’s enough to have 16k accounts in memory at a time. … 1000 similar reasoning steps later … And, therefore, TigerBeetle allocates all memory at a startup.

Note that the reasoning is basically repeated in code. We don’t allocate memory for 16k accounts. There’s only one constant, message_size_max = 1MiB, and everything else is derived in code. We compute transfers_count_size_max as divCeil(message_size_max, @sizeOf(transfers)), etc. It’s really quite amazing how compositional the whole thing turns out to be at the end, you never quite know the global limit in bytes, you derive local limits in the number of logical objects, you allocate those dynamically (at startup), and the not-known-up-front total is your allocation.

As another example, we’ve recently implemented a new CI system for TigerBeetle, and that also follows static allocation. CI system basically tracks job. To make static allocation work, we set a constraint that there can be at most N jobs at a time. What if we are very productive and need more than N? We just drop the oldest, the least relevant jobs. The universe of jobs is potentially infinite, but we take the N highest priority ones.


Regardless of these considerations, I highly recommend the following exercise: look at every function that both:

  • takes an Allocator argument,
  • contains a try statement.

and try to find memory management errors on paths that throw errors. In my experience, its highly likely that you will find a lot of bugs, which could teach you about error-prone patterns of managing memory.

Thank you for taking the time writing such a detailed and well understandable explanation :heart_exclamation: It really helps understanding those things.

I think I misconceived something. I thought allocating everything up front would be the most extreme variant of reserve first. But I now get that they’re two related but not identical things. It seems that static allocation at the beginning with zero additional allocations afterwards only works for some specific programmes (and is by no means trivial to accomplish). However, basic reserve first is already becoming my go-to workflow for those array stuff.

What I’m still curious about: Does it have (and if yes, which) any advantages initilazing an arena with a larger amount of memory or using a fixed buffer alloc for the assumed Max size of memory needed and only extra allocated if inevitable? Or is the there no such advantage, respectively it is negligible?

I think this comes down to the program you are writing and the restrictions you are working with. My guess is that the performance differences are negligible for most devices. However, working with an arena is much more convenient. What would be your approach if you need to allocate extra memory if your fixed buffer alloc is too small? I would use the pre-heated arena approach, unless the fixed buffer is better for my problem space.

I did notice that the arena in the standard library tends to grow it’s capacity to around 1.5 times the requested memory. So if you are working with limited RAM, the standard arena might not be a good fit for you.

In Zogue (my game-engine) I pre-heat my arenas with the amount of memory I know I will need at minimum. I have these helper functions for this:

pub fn preHeatAllocator(alloc: std.mem.Allocator, size: usize) void {
    if (size == 0) {
        return;
    }
    // Since this is just a pre-heat, it is better to let the
    // OOM error occur when the allocation is actually necessary.
    const ptr = alloc.alloc(u8, size) catch return;
    alloc.free(ptr);
}

/// Convenience function that calls preHeatAllocator on the Arena's allocator.
pub fn preHeatArena(arena: *std.heap.ArenaAllocator, size: usize) void {
    preHeatAllocator(arena.allocator(), size);
}

Take my opinion with the needed amount of salt. I would love to be corrected by someone with more experience.

Reserve first has many forms, but the extreme one means you decide how many “things” you support, allocate all the memory and the assign the “slots” during runtime, without asking for more memory.

For example, if you are doing a web server, you decide that you can handle up to 10k concurrent connections, each connection requires X+Y+Z data for it’s operations, so you can allocate all of that up front, and then you enforce the limits on all levels. You basically have various memory pools, from which you allocate. You limit how large requests you receive. If you lock the memory like tigerbeatle does, you guarantee it as stays in RAM, you get predictable behavior and it’s easier to reason about some problems if you know allocations can’t fail.

But it’s very application specific, imagine you had a text editor that allocates 4GB when it starts up. You probably wouldn’t like that. The extreme version of reserve first makes sense if the application is expected to have full control over the machine it’s running on.

On personal computers, you are better off sizing things dynamically, as multiple programs have to coexist and share the same limited memory, so it’s better to only ask for what you need. In this model, you still want to reserve first, but then it’s an optimization, not static requirement.

For example, when you are parsing some data structure, you either know or can guess how many items you need in an array, so you allocate for what you expect up front, but don’t abort if your estimate was slightly off, simply grow the allocation. Here you are playing with statistics. You want zero to one allocation per the normal case, but still handle the oversized cases.

The same applies to arenas, you are better off priming them to some size that you expect you need, but if you miscalculated and need more, then you let the arena to grow.

Some functions are transactional, you need to make sure it succeeds as one atomic block, or aborts everything. When you deal with memory in such situations, you typically allocate all the extra resources you need first, since it’s easy to handle OOM error on that level. You probably don’t want to create a file, and then append the file handle to an array and only then find our you got OOM, because that means you need to clean up the file, and even the cleanup can fail. So it’s better to reserve slot in the array first, then create the file, and them append assuming you already have the slot.

Thanks for that detailed addition.

Taking that specific case. Does it mean a solution like, the following one suggested by @gwenzek here, would be a good idea if I know my program usually needs about, let’s say 2MB of memory (but can exceed it in edge cases):

I wouldn’t copy that snippet, it unnecessarily touches the ArenaAllocator internals, you can just do alloc() followed by reset(.retain_capaciy).

However, whether you should use it depends on what your application does. ArenaAllocator is not a good allocator, if you want to use it over longer time, especially if you have growable structures inside. It would work, but you are wasting memory. That said, at 2MB for the entire program, that’s nothing, so you can ignore it. :slight_smile:

Yeah, we generally don’t do this. For static allocations, you don’t know the limit in bytes, you only know the logical limits (this hash map has N items, this array has M items). So we use a normal GPA. Generally, a fixed-sized area is just an admission that you don’t know the limit, and have to guesstimate it. Which sometimes happens!

A recent example of “arena exception” is our new API for doing subprocesses (we need our own, as the one in std is currently incompatible with static allocation). Over here:

The thing with subprocesses is that it’s really hard to predict just how much memory you need, for two reasons.

  • First, a subprocess might need to materialize a copy of parent environment, but the size of the environment can vary (a fun story about that).
  • Second, while logically you need a list of arguments, how that list is encoded varies per OS. In particular, on Windows you need to concatenate them into one big string, with appropriate escaping.
  • Third, not directly inherent, but, often, when you pass arguments to a process, you need some sort of string formatting and concatenation, which needs some extra memory as well.

It really seems like its not really possible to have a robustly correct upper bound here, so we go for a heuristic arena approach.

A Process is a re-usable resource, which stores an arena, which is used to spawn one child process. To spawn another one, you need to wait for the first one first.

When you create a Process, you pass in a gpa and an extra_spawn_size, a guesstimate of the amount of memory you need for args/env:

   var process = try Process.init(gpa, io, parent_environment, .{
        .working_directory = .cwd(),
        .spawn_size_extra = 4 * KiB,
    });

The constructor then allocates an arena, whose size is guesstimated based on the total size of the parent environment, plus the extra size passed in.

Passing arguments in can than OOM:

try process.arguments_format("-c user.name={name}", .{ .name = name });

But so far this works in practice (in our current usage, arguments either have static (but unknown) limits, or, if they can be too large, that’s a fair enough reason to reject a particular request). And, because of arenas, we don’t have to memory manage individual formatted strings, something tricky to get consistency right.


The emperor’s two naked butt cheeks here are:

  • Spawning a process of course requires dynamically allocating memory for the new process. This whole thing, in some sense, is an exercise in futility. We do it mostly for consistency’s sake, its just easier if everything’s uniformly static.
  • We currently use std.Io for actual process spawning, which doesn’t take a gpa and instead uses Io implementation global gpa sneakily. This feels like an API flaw to me. We do plan to transition to our own syscalling for process spawning anyway, so we don’t worry about that too much (to clarify, the Process API is used for various tooling things around TigerBeetle, we of course don’t shell out during transaction processing :rofl:)

Blog post please :folded_hands: