I'm testing an ESP32 device that sends data to a server every minute using HTTP POST. I noticed that the latency fluctuates heavily. For example, in one 20-minute test, the latency values (in microseconds) were:
1051330 213873 1035399 207991 619864 1236647 1437973 1439257 621018 2261337 1034008 1444945 1026229 683158 1379955 688353 1373319 1444669 1845595 208093
Here my code :
static void client_post_function()
{
int64_t start_time = esp_timer_get_time();
float a = 0.66;
float b = 3.25;
float c = 29.57;
float d = 65.78;
float d = 1008.44;
char json_data[256];
snprintf(json_data, sizeof(json_data), "{\"a\": %.2f, \"b\": %.2f, \"c\": %.2f, \"d\": %.2f, \"e\": %.2f}", a, b, c, d, e);
esp_http_client_config_t config_post = {
.url = "http://192.168.xx.xx:8080/post",
.method = HTTP_METHOD_POST,
.event_handler = client_post_handler};
esp_http_client_handle_t client_post = esp_http_client_init(&config_post);
esp_http_client_set_post_field(client_post, json_data, strlen(json_data));
esp_http_client_set_header(client_post, "Content-Type", "application/json");
printf("Sending: %s\n", json_data);
esp_err_t err = esp_http_client_perform(client_post);
int64_t end_time = esp_timer_get_time();
esp_http_client_cleanup(client_post);
uint32_t heap_after_post = esp_get_free_heap_size();
ESP_LOGI("HEAP", "Free heap AFTER HTTP POST : %d bytes", heap_after_post);
if(err == ESP_OK){
int64_t latency = end_time - start_time;
ESP_LOGI("LATENCY", "HTTP POST latency: %lld microseconds", latency);
} else{
ESP_LOGE("LATENCY", "HTTP POST failed");
}
}
static void periodic_post_task(void *pvParameters){
while (1)
{
client_post_function();
vTaskDelay(60000 / portTICK_PERIOD_MS);
}
}
Why is the latency fluctuating so widely? Could the ESP32 processing, Wi-Fi stability, or server response time be the main cause?
Latency depends on every network node that's in the path between the client and host, so it's hard to diagnose. 2.4 GHz WiFi frequencies are notoriously overloaded in populated areas, in which case packet latencies go to hell. Have you measured how a PC would behave in the same WiFi network?
ESP32 itself adds a fair bit of jitter through its WiFi power saving mode. Disable it through menuconfig by setting WIFI_PS_NONE