Cloud Functions with Pub/Sub triggers in GCP - Time & Space Complexity
When using Cloud Functions triggered by Pub/Sub messages, it is important to understand how the number of function executions grows as messages increase.
We want to know how the system behaves when more messages are published to the topic.
Analyze the time complexity of the following operation sequence.
// Cloud Function triggered by Pub/Sub
exports.processMessage = (message, context) => {
const data = Buffer.from(message.data, 'base64').toString();
console.log(`Processing message: ${data}`);
// Additional processing logic here
};
// Pub/Sub topic receives messages
// Each message triggers one function execution
This function runs once for each message published to the Pub/Sub topic.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Cloud Function execution triggered by each Pub/Sub message.
- How many times: Once per message published to the topic.
Each new message causes one new function execution, so the total executions grow directly with the number of messages.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 function executions |
| 100 | 100 function executions |
| 1000 | 1000 function executions |
Pattern observation: The number of executions grows linearly as messages increase.
Time Complexity: O(n)
This means the total work grows directly in proportion to the number of messages received.
[X] Wrong: "One function execution can handle all messages at once, so time stays the same as messages grow."
[OK] Correct: Each message triggers a separate function execution, so total executions increase with messages.
Understanding how event-driven functions scale with input size helps you design systems that handle load smoothly and predict costs.
"What if we batch multiple Pub/Sub messages into a single function execution? How would the time complexity change?"