How Much RAM Does a FreeRTOS Task Need? Measure It on ESP32
A FreeRTOS task costs its stack, plus a task control block (TCB), plus a bit of heap bookkeeping. The stack is the big part, and its size is the number you typed in by guesswork. 2048? 4096? Whatever the last example used?
ESP-IDF will tell you how close each task has come to running out, so you can stop guessing.
ESP-IDF counts stack in bytes, not words
In ESP-IDF, the stack size you pass to xTaskCreate is in bytes. So is the value returned by uxTaskGetStackHighWaterMark. Vanilla FreeRTOS documents both in words, and Espressif's documentation calls out the difference.
Quick detour, because this bites people porting code. On a 32-bit chip, a "stack depth of 1024" means 4096 bytes in vanilla FreeRTOS and 1024 bytes in ESP-IDF. The same line of C gets you a quarter of the stack, and the compiler has no opinion at all.
Measure one task's heap cost and peak stack
This program answers two separate questions: how much internal heap does creating the task take, and how much of its stack does the task use?
The worker waits for a notification before doing anything. That stops its own allocations (or those of the library calls it makes) landing in the middle of the heap measurement.
#include <stdio.h>
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define WORKER_STACK_BYTES 4096
static void worker(void *arg)
{
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
for (;;) {
/* Replace with your real work, including its worst path. */
char line[128];
snprintf(line, sizeof line, "uptime ticks: %u",
(unsigned)xTaskGetTickCount());
puts(line);
unsigned spare = (unsigned)uxTaskGetStackHighWaterMark(NULL);
printf("stack: peak used %u, never used %u bytes\n",
WORKER_STACK_BYTES - spare, spare);
vTaskDelay(pdMS_TO_TICKS(5000));
}
}
void app_main(void)
{
TaskHandle_t handle = NULL;
size_t before = heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
if (xTaskCreate(worker, "worker", WORKER_STACK_BYTES, NULL, 5, &handle) != pdPASS) {
puts("could not create worker");
return;
}
size_t after = heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
printf("task cost %u bytes of heap (stack %u, TCB about %u)\n",
(unsigned)(before - after), (unsigned)WORKER_STACK_BYTES,
(unsigned)sizeof(StaticTask_t));
xTaskNotifyGive(handle);
}
The first figure is the real price of the task on your build. Subtract the stack and you are left with the TCB and allocator overhead. I am deliberately not quoting a TCB size, because configuration options and IDF versions can change it.
The heap figure is a whole-system reading, so anything else allocating at that moment will pollute it. Run it early, before Wi-Fi and friends start, and be suspicious if it changes between boots.
The high water mark is the least free stack ever seen
The name sounds backwards. uxTaskGetStackHighWaterMark returns the smallest amount of stack that has been left over since the task started. A small number is bad. Peak usage is the stack size minus that number.
Hang on, how does it know? FreeRTOS fills a new stack with a known byte (0xA5), then counts how much of that pattern is still intact at the far end. It never tracks your function calls; it just looks for footprints in the snow.
This means that if a function reserves a large local array and only writes the first few bytes, the untouched part can still look unused. A longer input tomorrow writes further in, so test with the biggest inputs you accept.
A reading only covers the code that has run
If a task has only seen the happy path, the happy path is all you have measured. Before believing the number, force the ugly branches:
- Error handling and logging, especially formatted log messages.
- The largest message, packet or file you will accept.
- Network failures, reconnects and TLS handshakes, if the task does networking.
- Any recursion, such as parsing nested JSON.
- Callbacks that libraries run on your task's stack.
String formatting is notorious for eating stack, and Espressif's RAM guide singles out printf() and other string formatting as heavy users. Your measuring code above therefore costs stack too, so keep it in while testing and remember that removing it changes the result.
Floating point has its own surprise. In ESP-IDF, a task on the ESP32 that uses float gets pinned to the core it is running on, even if you created it unpinned. This has nothing to do with stack size, but it is an odd thing to discover by accident.
List every task to find the tight and the wasteful
You can read all the tasks at once with uxTaskGetSystemState, including ones ESP-IDF created for you. Enable CONFIG_FREERTOS_USE_TRACE_FACILITY in menuconfig first.
#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
void print_stacks(void)
{
/* A few spare slots in case tasks appear between the two calls. */
UBaseType_t cap = uxTaskGetNumberOfTasks() + 4;
TaskStatus_t *tasks = malloc(cap * sizeof *tasks);
if (tasks == NULL) {
puts("no memory for task list");
return;
}
UBaseType_t n = uxTaskGetSystemState(tasks, cap, NULL);
for (UBaseType_t i = 0; i < n; i++) {
printf("%-16s %u bytes never used\n", tasks[i].pcTaskName,
(unsigned)tasks[i].usStackHighWaterMark);
}
free(tasks);
}
Just after boot is too soon to call it, so wait until a long soak test has run. Call it from a task with room to spare, since it uses printf as well.
The system tasks have their own menuconfig settings, such as CONFIG_ESP_MAIN_TASK_STACK_SIZE and CONFIG_ESP_TIMER_TASK_STACK_SIZE. Trim those cautiously: Espressif warns that setting internal stacks too small makes ESP-IDF crash unpredictably.
Size from the peak, then leave a margin
My rule of thumb (an opinion, not an Espressif figure) is to take the worst peak you have seen, then add 25% or 512 bytes, whichever is more, and round up.
As an invented example, a 4096-byte stack reports 2300 bytes never used:
- Peak use is 4096 minus 2300, so 1796 bytes.
- Adding 25% gives 2245; adding 512 gives 2308.
- Take the larger and round up to 2560.
That saves 1536 bytes, which is nice with twenty similar tasks and hardly worth a risky afternoon with two.
The margin is there for paths you failed to trigger and for interrupts. ESP-IDF has a separate ISR stack, but you should not assume an interrupt costs the running task nothing, as saving its context takes room. Measure again after upgrading IDF, changing compiler optimisation or log levels, or updating a library.
Turn on overflow detection while you shrink
An overflow can corrupt neighbouring memory and crash somewhere unrelated, which is a miserable thing to debug. Give yourself a louder failure:
CONFIG_FREERTOS_CHECK_STACKOVERFLOWchecks for damaged canary bytes at context switches.CONFIG_FREERTOS_WATCHPOINT_END_OF_STACKuses a CPU watchpoint to trap a write near the end of the stack. It takes a watchpoint your debugger might want.CONFIG_COMPILER_STACK_CHECK_MODEenables GCC's stack protector, aimed at smashed stack frames.
None of these is proof. Espressif says the FreeRTOS checks cannot detect all overflows, so a quiet log does not replace the measurement.
Static allocation moves the cost, it does not remove it
xTaskCreateStatic lets you supply the stack and TCB yourself. The RAM then appears in the build's size report, and creation cannot fail halfway through the day because the heap is fragmented.
static StackType_t worker_stack[2560]; /* bytes on ESP-IDF */
static StaticTask_t worker_tcb;
/* Inside app_main or another function: */
TaskHandle_t handle = xTaskCreateStatic(worker, "worker", 2560, NULL, 5,
worker_stack, &worker_tcb);
If you reuse the worker above, change WORKER_STACK_BYTES to match, or its "peak used" line will be nonsense. It also still waits for xTaskNotifyGive(handle).
Got a board with PSRAM? Ordinary xTaskCreate still puts the stack and TCB in internal RAM. External stacks need a config option and static creation, and they come with restrictions because external RAM is inaccessible while the flash cache is disabled. I would measure and trim before going anywhere near that.
And if the task count is the real problem, check whether several of them spend their lives waiting for small, short jobs. One task reading from a queue needs one stack. The catch is that a slow job now delays everything behind it.