What causes a UserCodeTimeoutError?

Occasionally requests will take a really long time to process and eventually time out, showing the following error:

error: "UserCodeTimeoutError error"

What’s causing this and how do I fix it?

The XDN enforces a 20 second limit on request handling. You’ll see this error when your code exceeds this limit. Likely causes are:

  • A slow API - the request times out while waiting for the API to return a response.
  • An unhandled promise rejection leading to a response never being sent.
  • Legitimately slow code (this is the least likely cause)

In order to fix this, you need to determine the cause. To do so, I suggest using the Timing API to instrument your code and figure out what’s taking so long. I’d start by wrapping all fetch calls to your API in timing measurements:

import Timing from '@xdn/core/timing'

const timing = new Timing('api').start()

try {
  const result = await fetch(API_URL)
} finally {
  timing.end() // this will result in a `x-xdn-user-t: api=(millis)` response header

Then deploy your code and observe the x-xdn-user-t response header using Chrome devtools. Continue adding measurements until you find the bottleneck.

Note that if the request actually times out, you won’t see a x-xdn-user-t response header. But you should be able to extrapolate what’s causing the timeout by looking at requests that don’t time out and finding the largest component of handler execution time.