A quick note about Cloudflare worker global variable

Duy KN
1 min readMay 4, 2021

This is not actually an issue of Cloudflare Worker, my mistake instead. But I think it is quite interesting for someone who stayed in the same situation.

Let's start with this document Limits · Cloudflare Workers docs

Only one Workers instance runs on each of the many global Cloudflare edge servers. Each Workers instance can consume up to 128MB of memory. Use global variables to persist data between requests on individual nodes; note however, that nodes are occasionally evicted from memory.

So worker supports “global variable” with some limitation.

For my situation, I did not intend to use the global variable, but I did by mistake. This is my code:

cfn = await VM_CONFIG.get(vm, "json") || {}...return {config: cfn}

The cfn was not declared before. As a consequence, the worker treats it as a global variable. Then, the value of the return later is wrong sometimes.

From the beginning, I thought the issue comes from KV storage somehow, but quickly I find out it is a mistake. Value of “global variable” cfn was sometimes from another process that has just executed the get comment above.

The correct code should be:

let cfn = await VM_CONFIG.get(vm, "json") || {}

Takeaways

Do not forget to declare the scope variable you use in the worker. Once the output is wrong randomly, let double check if you use the “global variable” by a mistake.

--

--