Skip to main content

Instance Reuse

For a single invocation, a Cloud Function has two possible execution modes (the following uses the Node.js runtime as an example; other runtimes such as Python, PHP, Go, and Java follow the same mechanism):

  • Cold start: A brand-new runtime process must be spawned to load dependencies and run initialization code.
  • Warm start: The function instance and execution process are reused (referred to below as "instance reuse").

If a Cloud Function has not been invoked for some time, the platform will reclaim its allocated compute resources based on access patterns; on the next invocation, resources are reallocated, which triggers a cold start. When continuous requests are made to a Cloud Function, already-running instances are reused and can begin computation almost immediately — this is a warm start.

Tip

CloudBase automatically schedules and adjusts the number of instances based on your Cloud Function's long-term access patterns, ensuring good performance while saving resources.

State Residue Caused by Instance Reuse

Consider the following Cloud Function, which illustrates the state-residue issue caused by instance reuse:

let i = 0;
exports.main = async (event = {}) => {
i++;
console.log(i);
return i;
};

The first time this Cloud Function is invoked, it returns 1, as expected.

However, if the function is invoked repeatedly, the return value may increment starting from 2, or it may reset to 1 — this is the consequence of instance reuse:

  • On a warm start, the process executing the function is reused, its context is preserved, and therefore the variable i keeps incrementing.
  • On a cold start, the process is brand new and the code runs from the top, so it returns 1.

Therefore, developers should ensure that their Cloud Functions are stateless and idempotent — a single invocation must not depend on information left behind in the runtime by a previous invocation.

Leveraging Instance Reuse for Performance

Instance reuse is not just a caveat; it is also an optimization tool. Put one-time initialization logic outside the handler function so that subsequent warm-start requests can reuse established connections and preloaded resources, significantly reducing response latency.

// ✅ Recommended: initialize outside the handler; reused on warm starts
const mysql = require("mysql2/promise");

const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 5,
});

exports.main = async (event) => {
const [rows] = await pool.query("SELECT * FROM users WHERE id = ?", [
event.id,
]);
return rows;
};
// ❌ Not recommended: rebuilds the connection on every invocation, paying connection overhead on both cold and warm starts
exports.main = async (event) => {
const conn = await mysql.createConnection({
/* ... */
});
const [rows] = await conn.query("SELECT * FROM users WHERE id = ?", [
event.id,
]);
await conn.end();
return rows;
};

Similarly, HTTP clients, SDK clients, and read-only configuration loading should all be initialized outside the handler.

Common Pitfall: Untrusted Results from getWXContext()

In WeChat Mini Program CloudBase scenarios, a common instance-reuse pitfall is that cloud.getWXContext() sometimes returns inaccurate openId values.

// index.js
const cloud = require("wx-server-sdk");
exports.main = async (event, context) => {
// The openId, appId, and unionId retrieved here are trusted;
// note that unionId is only returned when the unionId retrieval conditions are met.
let { OPENID, APPID, UNIONID } = cloud.getWXContext();

return {
OPENID,
APPID,
UNIONID,
};
};

If the Cloud Function is always invoked from a Mini Program client, the results are trustworthy. However, if the same Cloud Function is invoked from multiple sources — Mini Program, Web, HTTP, and so on — problems can arise:

  • cloud.getWXContext() reads openId and related information from runtime environment variables.
  • Non–Mini Program invocations do not set these environment variables, but because of instance reuse, the process may still hold values left over from a previous Mini Program invocation.
  • As a result, a non–Mini Program invocation may occasionally read "someone else's openId," creating a privilege-escalation risk.

How to avoid this:

  • If you need cloud.getWXContext() to obtain user identity, make sure the Cloud Function is invoked only from a Mini Program client.
  • For mixed invocation scenarios, pass user identity explicitly via request parameters, or clear the relevant environment variables at the entry of the function.