DEV Community

Tim Nguyen
Tim Nguyen

Posted on

Avoid This Silent Timeout Bug with Axios in Lambda as proxy, ALB, and Content-Length

Have you ever encountered a 504 Gateway Timeout from your AWS Application Load Balancer (ALB) when proxying requests via Axios, even though everything looks right on the surface?

Here’s a tricky issue I ran into — and how to avoid it in the future.


💥 The Setup

You're using AWS Lambda using a Node.js proxy to forward a POST request to a backend behind ALB:

await axios.post('http://my-backend', {
  timestamp: '2025-06-10 10:49:46',
  token: 'fEjck23HJkLlrRkDKtNWVI:APA91bHphS5as...'
}, {
  headers: {
    'Content-Type': <keep it from original request>,
    'Content-Length': <get from original request>
  }
});
Enter fullscreen mode Exit fullscreen mode

Looks harmless, but suddenly:

504 Gateway Timeout from ALB
Enter fullscreen mode Exit fullscreen mode

And the backend logs show:

SyntaxError: Unterminated string in JSON at position xxx
Enter fullscreen mode Exit fullscreen mode

🧠 Root Cause
The error comes from a mismatch between the Content-Length and the actual body size.

What actually happens:

  • Axios serializes the data object to JSON.
  • You manually set Content-Length: xxx or forward it from orignial request, but the serialized body is longer.
  • The backend receives only the first xxx bytes.
  • It tries to parse, but the JSON is incomplete.
  • It waits for the rest of the body, but it never comes.
  • Eventually, the connection times out → ALB returns a 504.

❌ Why Not a 400?

  • Normally, a malformed JSON gives a 400 Bad Request.
  • But here:
    • The backend doesn't know the full body has been sent.
    • It thinks the rest is still coming.
    • So it never sends a response → ALB gives up and returns 504.

✅ The Fix

  • Just don’t manually set Content-Length. Let Axios compute it.
await axios.post('http://my-backend', {
  timestamp: '2025-06-10 10:49:46',
  token: 'fEjck23HJkLlrRkDKtNWVI:APA91b...'
}, {
  headers: {
    'Content-Type': <keep it from original request>
    // ✅ Do not manually set Content-Length
  }
});
Enter fullscreen mode Exit fullscreen mode

Axios will:

  • Serialize the object to JSON
  • Compute the correct length
  • Set the header automatically

Have fun coding!

Top comments (0)