Dealing with cycles limit exceeded errors

From Internet Computer Wiki
Jump to: navigation, search

What is the cycles limit exceeded error?

On the Internet Computer every update function call is limited to a certain hard-coded maximum runtime. This maximum runtime is called cycles limit. When one of your function calls tries to run longer that this limit, the function call is aborted and the canister state is rolled back to the state before the function call. When this happens, you may receive an error message that looks like this:

   Error: The Replica returned an error: code 5, message: "Canister <canisterid> exceeded the cycles limit for single message execution."

Common causes of cycles limit exceeded errors

There are a few common causes for this error:

  • Loops or recursion with bad termination conditions.
  • Copying lots of data to/from stable memory during pre_upgrade or post_upgrade.
  • Computing the hash of a large chunk of data.

Dealing with the cycles limit

Here's a few ideas to work around the cycles limit:

Speeding up your code

If you run into the cycles limit because of long-running computations, it may be beneficial to optimise your code. For recursive calls, see if memoization could help speed up your code.

Split up your work into multiple functions

Certain long-running operations can be split into multiple parts. For example, if you copy a large vector from stable memory within your post_upgrade function, you could only load the most necessary data (such as user accounts) during post_upgrade and then load other data in chunks with manual calls to other functions.

If you decide to split computation into multiple functions, make sure to put in the necessary safeguards to prevent your canister from breaking:

  • If you have a function that does a lot of one-time work, it shouldn't be possible to do the work many times. Otherwise a malicious user can burn cycles very quickly from your canister.
  • If your canister does not work properly before a certain amount of work is done, disable other functions by returning an error until the canister is ready.