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?"
Practice
Solution
Step 1: Understand Pub/Sub trigger behavior
Cloud Functions connected to Pub/Sub topics run automatically when a new message is published to that topic.Step 2: Confirm automatic execution
There is no need for manual start or keyword filtering by default; the function triggers on every message.Final Answer:
The function runs automatically when a new message arrives on the Pub/Sub topic. -> Option AQuick Check:
Pub/Sub triggers auto-run functions on new messages [OK]
- Thinking the function needs manual start
- Assuming filtering happens automatically
- Believing the function runs on a schedule
Solution
Step 1: Identify correct Cloud Function signature for Pub/Sub
In Node.js, a Pub/Sub triggered function uses (event, context) parameters, where event.data contains the message.Step 2: Check options for correct syntax
exports.myFunction = (event, context) => { console.log(event.data); }; uses exports with (event, context) and accesses event.data correctly. Others either use wrong parameters or HTTP function style.Final Answer:
exports.myFunction = (event, context) => { console.log(event.data); }; -> Option AQuick Check:
Pub/Sub functions use (event, context) signature [OK]
- Using HTTP function signature (req, res)
- Missing exports keyword
- Using wrong parameter names
def hello_pubsub(event, context):
import base64
message = base64.b64decode(event['data']).decode('utf-8')
print(f'Received message: {message}')What will be printed if the Pub/Sub message data is base64 encoding of 'Hello World'?
Solution
Step 1: Decode base64 message data
The function decodes event['data'] from base64 to bytes, then decodes bytes to UTF-8 string.Step 2: Print the decoded message
The decoded string is 'Hello World', so the print statement outputs 'Received message: Hello World'.Final Answer:
Received message: Hello World -> Option CQuick Check:
Base64 decode then UTF-8 decode gives original message [OK]
- Printing raw base64 string instead of decoded
- Forgetting to decode bytes to string
- Assuming event['data'] is plain text
Solution
Step 1: Check Pub/Sub subscription linkage
If the function is not linked to the correct Pub/Sub topic, it will not trigger on published messages.Step 2: Eliminate other causes
Syntax errors cause deployment failure, empty topics can still trigger if messages arrive, and Cloud Functions do support Pub/Sub triggers.Final Answer:
The function is not subscribed to the correct Pub/Sub topic. -> Option DQuick Check:
Correct topic subscription is required for triggers [OK]
- Assuming empty topic blocks triggers
- Ignoring subscription configuration
- Thinking Cloud Functions lack Pub/Sub support
Solution
Step 1: Understand Pub/Sub delivery guarantees
Pub/Sub guarantees at-least-once delivery, so duplicates can occur if retries happen.Step 2: Implement idempotency in function
To handle duplicates, the function should process messages idempotently, often by checking unique message IDs to avoid repeated work.Step 3: Evaluate other options
Disabling retries risks message loss, global variables don't persist across executions, and Pub/Sub does not guarantee exactly-once delivery by itself.Final Answer:
Implement idempotent processing in the function using unique message IDs. -> Option BQuick Check:
Idempotent code handles retries safely [OK]
- Expecting Pub/Sub to do exactly-once delivery
- Disabling retries risking lost messages
- Using non-persistent variables for tracking
Ready to prove it?
Pass the test and this pattern moves unknown
