Google Cloud Functions
- Cloud Functions is a serverless execution environment for building and connecting cloud services
- Cloud Functions provide scalable pay-as-you-go functions as a service (FaaS) to run code with zero server management.
- Cloud Functions are attached to events emitted from the cloud services and infrastructure and are triggered when an event being watched is fired.
- Cloud Functions supports multiple language runtimes including Node.js, Python, Go, Java, .Net, Ruby, PHP, etc.
- Cloud Functions features include
- Zero server management
- No servers to provision, manage or upgrade
- Google Cloud handles the operational infrastructure including managing servers, configuring software, updating frameworks, and patching operating systems
- Provisioning of resources happens automatically in response to events
- Automatically scale based on the load
- Cloud Function can scale from a few invocations a day to many millions of invocations without any work from you.
- Integrated monitoring, logging, and debugging capability
- Built-in security at role and per function level based on the principle of least privilege
- Cloud Functions uses Google Service Account credential to seamlessly authenticate with the majority of Google Cloud services
- Key networking capabilities for hybrid and multi-cloud scenarios
- Zero server management
Cloud Functions Execution Environment
- Cloud Functions handles incoming requests by assigning them to instances of the function and based on the volume or existing functions, it can assign it to an existing one or spawn a new instance.
- Each instance of a function handles only one concurrent request at a time and can use the full amount of resources i.e. CPU and Memory
- Cloud Functions may start multiple new instances to handle requests, thus provide auto-scaling and parallelism.
- Cloud Functions must be stateless i.e. one function invocation should not rely on an in-memory state set by a previous invocation, to allow Google to automatically manage and scale the functions
- Every deployed function is isolated from all other functions – even those deployed from the same source file. In particular, they don’t share memory, global variables, file systems, or other state.
- Cloud Functions allows you to set a limit on the total number of function instances that can co-exist at any given time
- Cloud Function instance is created when its deployed or the function needs to be scaled
- Cloud Functions can have a Cold Start, which is the time involved in loading the runtime and the code.
- Function execution time is limited by the timeout duration specified at function deployment time. By default, a function times out after 1 minute but can be extended up to 9 minutes.
- Cloud Function provides a writeable filesystem i.e.
/tmp
directory only, which can be used to store temporary files in a function instance. The rest of the file system is read-only and accessible to the function - Cloud Functions has 2 scopes
- Global Scope
- contain the function definition,
- is executed on every cold start, but not if the instance has already been initialized.
- can be used for initialization like database connections etc.
- Function Scope
- only the body of the function declared as the entry point
- is executed for each request and should include the actual logic
- Global Scope
- Cloud Functions Execution Guarantees
- Functions are typically invoked once for each incoming event. However, Cloud Functions does not guarantee a single invocation in all cases
- HTTP functions are invoked at most once as they are synchronous and the execution is not retried in an event of a failure
- Event-driven functions are invoked at least once as they are asynchronous and can be retried
Cloud Functions Events and Triggers
- Events are things that happen within the cloud environment that you might want to take action on.
- Trigger is creating a response to that event. Trigger type determines how and when the function executes.
- Cloud Functions supports the following native trigger mechanisms:
- HTTP Triggers
- Cloud Functions can be invoked with an HTTP request using the
POST
,PUT
,GET
,DELETE
, andOPTIONS
HTTP methods - HTTP invocations are synchronous and the result of the function execution will be returned in the response to the HTTP request.
- Cloud Functions can be invoked with an HTTP request using the
- Cloud Endpoints Triggers
- Cloud Functions can be invoked through Cloud Endpoints, which uses the Extensible Service Proxy V2 (ESPv2) as an API gateway
- ESPv2 intercepts all requests to the functions and performs any necessary checks (such as authentication) before invoking the function. ESPv2 also gathers and reports telemetry
- Cloud Pub/Sub Triggers
- Cloud Functions can be triggered by messages published to Pub/Sub topics in the same Cloud project as the function.
- Pub/Sub is a globally distributed message bus that automatically scales as needed and provides a foundation for building robust, global services.
- Cloud Storage Triggers
- Cloud Functions can respond to change notifications emerging from Google Cloud Storage.
- Notifications can be configured to trigger in response to various events inside a bucket – object creation, deletion, archiving, and metadata updates.
- Cloud Functions can only be triggered by Cloud Storage buckets in the same Google Cloud Platform project.
- Direct Triggers
- Cloud Functions provides a
call
command in the command-line interface and testing functionality in the Cloud Console UI to support quick iteration and debugging - Function can be directly invoked to ensure it is behaving as expected. This causes the function to execute immediately, even though it may have been deployed to respond to a specific event.
- Cloud Functions provides a
- Cloud Firestore
- Cloud Functions can handle events in Cloud Firestore in the same Cloud project as the function.
- Cloud Firestore can be read or updated in response to these events using the Firestore APIs and client libraries.
- Analytics for Firebase
- Firebase Realtime Database
- Firebase Authentication
- Cloud Functions can be triggered by events from Firebase Authentication in the same Cloud project as the function.
- HTTP Triggers
- Cloud Functions can also be integrated with any other Google service that supports Cloud Pub/Sub for e.g. Cloud Scheduler, or any service that provides HTTP callbacks (webhooks)
- Google Cloud Logging events can be exported to a Cloud Pub/Sub topic from which they can then be consumed by Cloud Functions.
Cloud Functions Best Practices
- Write Idempotent functions – produce same events when invoke multiple times with the same parameters
- Do not start background activities i.e. activity after function has terminated. Any code run after graceful termination cannot access the CPU and will not make any progress.
- Always delete temporary files – As files can persist between invocations, failing to delete files may lead to memory issues
- Use dependencies wisely – Import only what is required as it would impact the cold starts due to invocation latency
- Use global variables to reuse objects in future invocations for e.g. database connections
- Do lazy initialization of global variables
- Use retry to handle only transient and retryable errors, with the handling being idempotent
GCP Certification Exam Practice Questions
- Questions are collected from Internet and the answers are marked as per my knowledge and understanding (which might differ with yours).
- GCP services are updated everyday and both the answers and questions might be outdated soon, so research accordingly.
- GCP exam questions are not updated to keep up the pace with GCP updates, so even if the underlying feature has changed the question might not be updated
- Open to further feedback, discussion and correction.