Category
Serverless
1. Introduction
What this service is
Alibaba Cloud Function Compute is a fully managed serverless compute service that runs your code in response to events (HTTP requests, schedules, and service events) without you provisioning or managing servers.
Simple explanation (one paragraph)
You upload a function, connect it to a trigger (for example, an HTTP endpoint or an OSS object-created event), and Function Compute automatically runs your code only when needed—scaling up during traffic spikes and scaling down when idle—while you pay based on actual usage.
Technical explanation (one paragraph)
Function Compute provides a regional control plane for creating services, functions, versions/aliases, and triggers. The platform schedules function instances on demand, allocates CPU proportional to your configured memory, supports multiple runtimes (and custom runtimes/containers where available), integrates with Alibaba Cloud networking (VPC), observability (Log Service / CloudMonitor), and identity (RAM), and offers operational controls such as concurrency settings and staged releases via versions and aliases (verify exact feature names and availability per region in the official docs).
What problem it solves
Function Compute solves the operational burden of running small-to-medium compute workloads—API backends, event processing, automation jobs, and glue code—by eliminating server management, reducing idle capacity waste, and providing built-in scaling, logging, and integrations with the Alibaba Cloud ecosystem.
2. What is Function Compute?
Official purpose
Function Compute is Alibaba Cloud’s serverless function platform for running event-driven code. It is designed to execute short-lived or event-triggered workloads with automatic scaling and pay-as-you-go billing.
Core capabilities – Run code in managed runtimes (and custom runtimes/containers where supported). – Trigger execution from events such as HTTP requests, timers (schedules), and other Alibaba Cloud services. – Provide operational constructs for organizing and deploying functions: services, triggers, versions, and aliases. – Integrate with Alibaba Cloud IAM (RAM), VPC networking, and observability (Log Service, CloudMonitor).
Major components – Service: A logical container for one or more functions, often used to share configuration such as networking, logging, and permissions (service role). – Function: Your deployed code + runtime + resource configuration (memory, timeout, environment variables). – Trigger: Event source mapping (for example, HTTP trigger, OSS trigger, timer trigger). Trigger types vary by region and platform version—verify in official docs. – Version / Alias: Deployment lifecycle primitives for immutable function versions and stable pointers (aliases) for traffic shifting and rollbacks (verify exact behavior for your trigger type). – Logs / Metrics: Integration with Alibaba Cloud Log Service (SLS) and CloudMonitor.
Service type
Managed serverless compute (Functions-as-a-Service / FaaS).
Scope (regional / account / project) – Regional: Function Compute resources are created in a specific Alibaba Cloud region. Choose the region close to your users and dependent services (OSS buckets, databases, etc.). – Account-scoped: Resources belong to your Alibaba Cloud account and are governed by RAM permissions. – Service/function-scoped settings: Many settings (execution role, VPC attachment, logging) are configured at the service level and inherited by functions.
How it fits into the Alibaba Cloud ecosystem Function Compute commonly sits between: – Ingress: HTTP clients, API Gateway (if used), or direct HTTP triggers. – Event sources: OSS, EventBridge, message services, and scheduled events. – Data services: ApsaraDB (RDS/PolarDB), Tablestore, Redis, and OSS. – Ops: Log Service (SLS), CloudMonitor, ActionTrail (auditing), and RAM for identity and access.
Naming status: As of the latest available documentation up to this writing, the service is still named Function Compute on Alibaba Cloud. If you encounter “Function Compute 3.0” branding or platform version references in docs, treat those as platform evolution rather than a different product; always follow the region-specific console and official docs for the current workflow.
3. Why use Function Compute?
Business reasons
- Lower operational overhead: No server provisioning, patching, or capacity planning for bursty workloads.
- Cost alignment to usage: Pay primarily for executions and configured resources rather than always-on instances (details vary by region and billing rules—see pricing section).
- Faster time-to-market: Teams can ship features as small functions and connect them to events quickly.
Technical reasons
- Event-driven architecture: Clean fit for integrations, automation, and stream/message-driven processing.
- Elastic scaling: The platform automatically scales instances to match incoming events.
- Language/runtime flexibility: Supports multiple runtimes plus custom runtime/container options where available (verify supported runtimes per region).
Operational reasons
- Managed reliability: Alibaba Cloud operates the underlying compute fleet and scheduler.
- Built-in observability hooks: Logging to SLS, metrics to CloudMonitor; integrates with tracing solutions where supported (for example ARMS—verify in official docs).
- Deployment safety: Versions and aliases support safer releases and rollbacks (verify trigger compatibility).
Security/compliance reasons
- RAM-based access control: Fine-grained permissions for who can deploy/invoke/manage functions.
- Execution roles: Functions can access other Alibaba Cloud services using a RAM role rather than long-lived access keys.
- Auditability: Many administrative actions can be audited via Alibaba Cloud audit services (for example ActionTrail—verify your account configuration).
Scalability/performance reasons
- Scale-to-zero: Idle workloads can scale down to near-zero running resources.
- Concurrency controls: Manage burst behavior and protect downstream services (feature names and exact controls vary—verify in docs).
- Latency optimization options: Use provisioned/pre-warmed capacity if supported in your region to reduce cold starts (verify).
When teams should choose it
- APIs with variable traffic, webhooks, and backend-for-frontend (BFF) endpoints.
- Event processing for object storage, logging pipelines, and integration workflows.
- Scheduled jobs and automation that would otherwise require a VM or container running 24/7.
- Lightweight data transformations and glue logic between Alibaba Cloud services.
When teams should not choose it
- Long-running compute (hours) or workloads exceeding Function Compute time limits.
- Highly stateful services that need stable local disks or long-lived connections without redesign.
- Ultra-low-latency workloads that cannot tolerate cold starts and where provisioned capacity is not acceptable or too costly.
- Applications needing full OS-level control, specialized drivers, or complex networking not supported by the serverless environment.
4. Where is Function Compute used?
Industries
- E-commerce: image resizing on upload, order webhooks, flash-sale event handlers.
- Media & entertainment: transcoding orchestration, thumbnail generation, metadata extraction.
- Finance & fintech: event-based risk checks, reconciliation tasks, alert enrichment (with strict security controls).
- Gaming: backend event processing, telemetry enrichment, scheduled maintenance tasks.
- Manufacturing/IoT: device event processing via messaging/event buses.
- SaaS: multi-tenant webhooks, scheduled billing jobs, and integration connectors.
Team types
- Platform engineering teams building internal developer platforms.
- DevOps/SRE teams automating operations and remediation.
- Application teams building APIs and event-driven components.
- Data engineering teams building lightweight ingestion and transformation steps.
Workloads
- HTTP micro-APIs, webhooks, and callback receivers.
- Storage events (for example OSS object create) for processing pipelines.
- Scheduled tasks (cron-like).
- Message/event consumption (through Alibaba Cloud messaging/eventing services).
Architectures
- Event-driven serverless microservices.
- Hybrid architectures: ACK/containers for long-running services + Function Compute for bursty tasks.
- Data lake pipelines: OSS + Function Compute + Log Service/analytics.
- Security automation: event triggers + function-based enrichment + ticketing/notification.
Production vs dev/test usage
- Dev/test: fast iteration on functions, staging triggers, validating IAM policies, and cost modeling.
- Production: often paired with versions/aliases, strict RAM policies, VPC connectivity to private data stores, and robust logging/monitoring.
5. Top Use Cases and Scenarios
Below are realistic patterns where Alibaba Cloud Function Compute is a strong fit.
1) HTTP API endpoint (serverless backend)
- Problem: You need a small API without running ECS instances 24/7.
- Why Function Compute fits: Built-in HTTP triggers and autoscaling for request bursts.
- Example: A
/pricing/quoteendpoint that calls an internal pricing service or database and returns a JSON quote.
2) Webhook receiver for third-party SaaS
- Problem: Webhooks arrive unpredictably; idle servers waste money.
- Why it fits: Scale-to-zero and fast event handling.
- Example: Stripe/GitHub webhook calls an HTTP trigger; function validates signature and writes events to a queue.
3) OSS upload processing (images/documents)
- Problem: New objects land in OSS and must be resized/scanned/converted.
- Why it fits: Storage event triggers and short-lived compute.
- Example: When a user uploads an image to OSS, a function generates thumbnails and writes them back to OSS.
4) Scheduled jobs (cron replacement)
- Problem: Daily/weekly jobs run briefly but traditionally need a VM.
- Why it fits: Timer triggers with per-invocation billing.
- Example: Nightly cleanup of expired sessions in Redis and sending a summary report.
5) Log enrichment and routing
- Problem: Logs need enrichment (geo-IP, user mapping) before indexing or alerting.
- Why it fits: Integration with Log Service triggers (where supported) and quick transformations.
- Example: Parse WAF logs, enrich with asset metadata, and forward critical events to an alerting system.
6) EventBridge-based integration workflows
- Problem: You want loose coupling between producers and consumers.
- Why it fits: Functions subscribe to event buses and respond independently.
- Example: “OrderCreated” event triggers inventory reservation and notification functions.
7) Lightweight ETL for analytics
- Problem: Transform small batches as they arrive without running a Spark cluster.
- Why it fits: Event-driven transformations for small/medium data volumes.
- Example: Convert uploaded CSV files to normalized JSON lines and store to OSS for downstream analytics.
8) Security automation and remediation
- Problem: Respond to security signals quickly and consistently.
- Why it fits: Automated actions on events, with controlled IAM roles.
- Example: On a suspicious login alert, a function tags the user, notifies security, and rotates keys (subject to approvals).
9) Chatbot / messaging glue code
- Problem: You need a thin adapter between a chat platform and internal systems.
- Why it fits: HTTP endpoints + fast execution.
- Example: A chatbot command triggers a function that queries CMDB and returns host status.
10) Multi-tenant SaaS background tasks
- Problem: Tenant jobs run sporadically and scale unevenly.
- Why it fits: Concurrency scaling and cost per execution.
- Example: Tenant-specific nightly billing aggregation tasks triggered by a schedule, partitioned by tenant ID.
11) Async offloading from web apps
- Problem: Web request path must remain fast while heavy work happens in the background.
- Why it fits: Pair HTTP trigger with a queue/event bus and a worker function.
- Example: API accepts request, writes a job message, returns 202; worker function renders a PDF.
12) Custom authentication/authorization middleware
- Problem: A centralized auth layer is needed for multiple APIs.
- Why it fits: Functions can implement token validation and policy checks.
- Example: An auth function validates JWTs and issues short-lived signed URLs for OSS downloads.
6. Core Features
Feature availability can vary by region and platform version. Always confirm in the official Alibaba Cloud Function Compute documentation for your region.
1) Managed runtimes (and language support)
- What it does: Provides managed language runtimes (for example Node.js, Python, Java, etc.) so you deploy code without managing OS images.
- Why it matters: Faster development and fewer operational concerns.
- Practical benefit: Standard runtime patching and consistent execution environment.
- Caveats: Runtime versions deprecate over time; plan upgrades and pin versions carefully.
2) Custom runtime / custom container (where supported)
- What it does: Run code in a custom runtime or container image for non-standard stacks.
- Why it matters: Enables specialized dependencies and tighter environment control.
- Practical benefit: Port existing services/tools into serverless with fewer rewrites.
- Caveats: Larger images can increase cold-start time; security scanning and patching become your responsibility.
3) Triggers (event sources)
- What it does: Connects functions to events such as HTTP requests, OSS events, timers, and event bus/messaging services.
- Why it matters: Enables event-driven architectures.
- Practical benefit: Glue together Alibaba Cloud services without managing always-on workers.
- Caveats: Each trigger type has its own delivery semantics, retries, and payload formats—verify for your trigger.
4) Services and shared configuration
- What it does: Organizes functions into services with shared IAM role, VPC config, and logging config.
- Why it matters: Simplifies multi-function apps and governance.
- Practical benefit: One place to set execution role and network access.
- Caveats: Overloading a single service with unrelated functions can complicate IAM and change management.
5) Versions and aliases (release management)
- What it does: Publish immutable versions and route stable traffic via aliases (for example
dev,staging,prod). - Why it matters: Safer deployments, rollbacks, and controlled releases.
- Practical benefit: Promote the same artifact across environments.
- Caveats: Confirm how triggers bind to versions/aliases in your region; some event sources may need explicit configuration.
6) Concurrency and scaling controls
- What it does: Scales function instances based on incoming events; provides controls to limit concurrency and protect downstream dependencies.
- Why it matters: Prevents “serverless stampedes” that overload databases.
- Practical benefit: Predictable load on RDS/Redis and stable latency.
- Caveats: Hard limits can cause throttling; design retry/backoff and queue buffering.
7) VPC integration (private networking)
- What it does: Allows functions to access private resources in your VPC (databases, caches, internal services).
- Why it matters: Many production workloads must not expose data services publicly.
- Practical benefit: Keep RDS/Redis private while still using serverless compute.
- Caveats: Internet access from VPC often requires NAT Gateway; misconfiguration commonly causes timeouts.
8) Observability integrations (logs/metrics)
- What it does: Sends execution logs to Log Service (SLS) and metrics to CloudMonitor.
- Why it matters: Debugging and SRE operations depend on visibility.
- Practical benefit: Correlate errors, latency, and invocation patterns.
- Caveats: Log retention and indexing cost money; apply retention policies.
9) Environment variables and configuration management
- What it does: Pass configuration to functions without code changes.
- Why it matters: Supports environment separation and safer deployments.
- Practical benefit: Store non-secret config (feature flags, endpoints) outside code.
- Caveats: Do not store secrets in plain environment variables unless you have a secure secret strategy (see Security section).
10) Layer/shared code mechanism (where supported)
- What it does: Share libraries/dependencies across multiple functions.
- Why it matters: Reduces duplication and simplifies upgrades.
- Practical benefit: Centralized dependency management.
- Caveats: Version and dependency compatibility still needs governance and testing.
7. Architecture and How It Works
High-level architecture
Function Compute has a managed control plane and a managed data plane: – Control plane: You create/update services, functions, triggers, roles, and versions via console, APIs, and tooling. – Data plane: The platform provisions execution environments (“instances”), routes events to them, scales them, and captures logs/metrics.
Request/data/control flow (typical)
- An event source (HTTP client, OSS, timer, EventBridge, etc.) emits an event.
- The trigger delivers the event to Function Compute.
- Function Compute selects or creates an execution instance and runs your handler.
- The function optionally calls other services (OSS/RDS/Redis) using RAM permissions and network configuration.
- Logs and metrics are emitted to SLS/CloudMonitor for analysis and alerting.
Common integrations (Alibaba Cloud ecosystem)
- OSS: Object-created events and storage for artifacts/data.
- Log Service (SLS): Centralized log storage, search, dashboards, alerts.
- CloudMonitor: Metrics and alerting.
- RAM: IAM for deploy/invoke/admin and execution roles.
- VPC / NAT Gateway: Private networking and egress.
- EventBridge: Event routing and decoupling (where used).
- API Gateway: API management layer (optional; some teams use HTTP triggers directly).
Dependency services
Function Compute itself is “serverless,” but production solutions typically rely on: – A logging backend (SLS) – A secrets/config strategy (KMS/Secrets Manager patterns—verify Alibaba Cloud offerings and your org standard) – Networking components (VPC, security groups, NAT) if private access is required
Security/authentication model
- Administrative access: RAM users/roles with Function Compute permissions.
- Invocation access:
- HTTP triggers can be open or protected depending on auth mode and configuration.
- Service-to-service invocations use RAM and signed requests where applicable.
- Execution permissions: A RAM role attached to the service/function grants access to other Alibaba Cloud APIs without embedding access keys.
Networking model
- Default: Function runs in an Alibaba Cloud-managed network.
- Optional: Attach to your VPC to reach private endpoints.
- For outbound internet from a VPC-attached function, you typically need NAT Gateway (and correct route tables), otherwise requests may time out.
Monitoring/logging/governance considerations
- Standardize log structure (JSON logs) so they’re searchable.
- Emit correlation IDs (request ID / trace ID) in logs.
- Use tags and naming standards for services/functions to support cost allocation and audits.
- Set SLS retention to control long-term cost.
Simple architecture diagram (Mermaid)
flowchart LR
U[User / Client] -->|HTTP request| HT[Function Compute HTTP Trigger]
HT --> FC[Function Compute Function]
FC --> OSS[OSS / Data Storage]
FC --> SLS[Log Service (SLS)]
FC --> CM[CloudMonitor Metrics]
Production-style architecture diagram (Mermaid)
flowchart TB
subgraph Internet
C[Web / Mobile Clients]
SaaS[3rd-party Webhooks]
end
subgraph AlibabaCloud[Alibaba Cloud Region]
WAF[WAF / Edge Protection (optional)]
APIGW[API Gateway or Direct HTTP Trigger]
FCsvc[Function Compute Service]
FCapi[HTTP Functions]
FCwrk[Async Worker Functions]
EB[EventBridge (optional)]
MQ[Messaging Service (optional)]
VPC[VPC]
RDS[ApsaraDB RDS/PolarDB (private)]
Redis[Redis (private)]
OSS[OSS Buckets]
NAT[NAT Gateway (egress)]
SLS[Log Service (SLS)]
CM[CloudMonitor]
AT[ActionTrail (audit)]
end
C --> WAF --> APIGW --> FCapi
SaaS --> APIGW --> FCapi
FCapi -->|emit event| EB
EB --> FCwrk
FCapi --> OSS
FCwrk --> OSS
FCapi --> VPC
FCwrk --> VPC
VPC --> RDS
VPC --> Redis
VPC --> NAT --> Internet
FCapi --> SLS
FCwrk --> SLS
FCapi --> CM
FCwrk --> CM
APIGW --> AT
FCsvc --> AT
8. Prerequisites
Account and billing
- An active Alibaba Cloud account with billing enabled (pay-as-you-go is common for Function Compute).
- Ensure your account has access to Function Compute in your target region.
Permissions (RAM)
You typically need: – Permissions to manage Function Compute resources (services/functions/triggers). – Permissions to create/attach a RAM role for function execution. – Permissions for dependent services used in the lab: – Log Service (SLS) project/logstore creation and write permissions – (Optional) OSS bucket access if you add OSS integration
A least-privilege approach is recommended. For learning, administrators often start with broad permissions and then tighten them.
Tools (optional but recommended)
You can complete the lab with the console only. Optional tools:
– curl for HTTP testing
– A local code editor
– Optional deployment tooling:
– Serverless Devs (Alibaba Cloud’s recommended serverless developer tool in many official materials). Official site: https://www.serverless-devs.com/
– Older toolchains such as Funcraft may appear in older tutorials; treat them as legacy and verify current recommendations in official docs.
Region availability
- Function Compute is regional. Pick one region and keep all dependent resources (SLS, OSS, databases) in the same region when possible to reduce latency and avoid cross-region data transfer.
Quotas/limits
Common limits to plan for (verify current values in official docs): – Maximum execution timeout per invocation – Memory range and CPU allocation model – Concurrency limits per function/service/account/region – Package size / deployment artifact limits – Trigger-specific throughput and payload size limits
Prerequisite services
For this tutorial lab: – Function Compute – Log Service (SLS) (recommended for visibility; some setups can auto-create required log resources if you grant permissions)
9. Pricing / Cost
Do not rely on blog posts for exact pricing. Function Compute pricing varies by region and sometimes by feature set. Always verify in the official pricing page and your Alibaba Cloud billing console.
Official pricing sources
- Pricing page (verify current URL and region selector): https://www.alibabacloud.com/product/function-compute/pricing
- Alibaba Cloud pricing calculator (if available for your account/region): https://www.alibabacloud.com/pricing/calculator
Pricing dimensions (typical for FaaS)
Function Compute costs are usually driven by: – Number of invocations (requests) – Execution duration (billed in time units) multiplied by – Allocated memory (and CPU proportional to memory) – Provisioned/pre-warmed capacity (if you enable it, you may pay for reserved capacity even when idle—verify the exact billing model in your region) – Outbound data transfer (internet egress) – Other service costs triggered by your function: – Log Service ingestion, indexing, storage, retention – NAT Gateway processing and bandwidth (if VPC egress is needed) – OSS requests and storage – Database calls, cache usage, EventBridge events, message service requests
Free tier / free quotas
Alibaba Cloud may offer free trials or free quotas depending on region, promotions, or new-user programs. Verify in official pricing and your account’s “Free Trial” offers. Do not assume a permanent free tier.
Cost drivers (what typically increases your bill)
- Increasing memory to reduce latency (higher cost per ms).
- High invocation rate (especially with chatty microservices).
- Large response payloads (bandwidth/egress).
- Heavy logs (debug logging in production).
- Enabling provisioned capacity 24/7 “just in case”.
- VPC egress through NAT Gateway for every invocation.
Hidden/indirect costs to plan for
- Log Service indexing: Indexing everything is convenient but can be expensive.
- Cross-zone/region traffic: If your function in Region A calls a database in Region B, you may pay more and suffer higher latency.
- Retry storms: Misconfigured retries can multiply invocations and downstream calls.
- Timeouts: Timeouts still consume billed compute time.
Network/data transfer implications
- Inbound requests are usually not billed as bandwidth in the same way as outbound internet traffic, but internet egress commonly is.
- Private endpoints (VPC/internal endpoints for OSS/RDS where available) can reduce public egress and improve security.
How to optimize cost (practical checklist)
- Right-size memory based on measured latency and CPU needs.
- Reduce invocation count by batching events where possible.
- Use asynchronous buffering (queues/event bus) to smooth spikes.
- Set log level to
INFOorWARNin production and cap payload sizes. - Apply SLS retention policies and selective indexing.
- Avoid unnecessary NAT egress; use internal endpoints when possible.
- Use reserved/provisioned capacity only for latency-critical functions and only during needed hours (if supported).
Example low-cost starter estimate (no fabricated prices)
A small hobby API might have: – A single HTTP function – Low traffic (hundreds to thousands of requests/day) – Small memory (128–256 MB) – Minimal logging and no VPC
In many regions, this can remain very low-cost because you only pay for actual usage. Use the pricing calculator with: – invocations/day – average duration (ms) – memory setting – log ingestion estimate (MB/day)
Example production cost considerations
For production, focus on: – Peak concurrency and whether you need provisioned capacity to meet p99 latency. – NAT Gateway costs if every invocation calls external services. – Log ingestion/indexing scale. – Cost of downstream services (database, cache, queue, EventBridge). – Multi-environment duplication (dev/stage/prod) and how often load tests run.
10. Step-by-Step Hands-On Tutorial
Objective
Deploy a real Function Compute HTTP endpoint that returns JSON, writes structured logs to Log Service (SLS), and uses environment variables—then validate behavior and clean up safely.
Lab Overview
You will:
1. Create a Function Compute Service with logging enabled.
2. Create a Function (Python example) and deploy code.
3. Add an HTTP Trigger and invoke it with curl.
4. Validate logs in SLS and basic metrics.
5. Clean up all resources.
This lab is designed to be low-cost and beginner-safe.
Step 1: Choose a region and confirm prerequisites
- Log in to the Alibaba Cloud console.
- Select a region where Function Compute is available (top navigation region selector).
- Confirm you can access: – Function Compute console – Log Service (SLS) console
Expected outcome: You can open the Function Compute console in your chosen region.
Verification – Function Compute console loads and shows you can create a service/function.
Step 2: (Recommended) Prepare Log Service (SLS) for function logs
Function Compute commonly integrates with Log Service (SLS) to store execution logs.
- Open Log Service in the same region.
- Create (or select) an SLS Project (a container for logstores).
- Create a Logstore for Function Compute logs (name example:
fc-tutorial-logstore). - Note the project and logstore names.
Expected outcome: You have an SLS project and logstore ready.
Verification – In Log Service, you can see the project and logstore created.
Common error – Permission denied creating SLS resources: Use a RAM user/role with sufficient permissions, or ask your administrator.
Step 3: Create a Function Compute Service
A Service is a logical container that can hold one or more functions.
- Open Function Compute console (same region).
- Create a new Service.
- Configure:
– Service Name:
fc-http-tutorial-service– Logging: Enable logging and select your SLS Project and Logstore. – Role (Execution Role):- If prompted, create/select a RAM role for Function Compute to write logs and (later) access other Alibaba Cloud services.
- Use least privilege in production. For this lab, ensure the role can write logs to SLS.
- Leave VPC disabled for now (to reduce complexity). You’ll learn VPC patterns later.
Expected outcome: Service is created and visible in Function Compute.
Verification – The service appears in the Function Compute service list. – Logging configuration shows your SLS project/logstore.
Common errors and fixes – Cannot assume role / role not found: Ensure the RAM role exists and trusts Function Compute (trust policy set by the console wizard). – Log writing fails later: Ensure the role has permissions to write to SLS.
Step 4: Create an HTTP function (Python) inside the service
- Inside your service, choose Create Function.
- Select a runtime: choose an available Python 3.x runtime in the console (exact versions vary by region).
-
Configure: – Function Name:
hello-http– Handler:index.handler– Memory: start small (for example 128 MB or 256 MB) – Timeout: 10 seconds (enough for a simple HTTP response) – Environment variables:APP_NAME=fc-http-labSTAGE=dev
-
In the function code editor, create
index.pywith the following:
# index.py
import os
import json
import datetime
def handler(event, context):
app_name = os.getenv("APP_NAME", "unknown")
stage = os.getenv("STAGE", "unknown")
# Basic structured log (appears in SLS if logging is enabled)
log_entry = {
"ts": datetime.datetime.utcnow().isoformat() + "Z",
"app": app_name,
"stage": stage,
"message": "Function invoked",
}
print(json.dumps(log_entry, ensure_ascii=False))
# HTTP trigger event formats can vary depending on the trigger type/version.
# Keep the response simple and JSON-based.
response = {
"ok": True,
"app": app_name,
"stage": stage,
"note": "Hello from Alibaba Cloud Function Compute",
}
return response
- Deploy/save the function.
Expected outcome: Function is created and deployed successfully.
Verification – Function status indicates it is deployed/active. – “Test” (if available) returns a JSON response.
Common errors and fixes
– Handler not found: Ensure file name is index.py and handler is index.handler.
– Syntax errors: Re-check indentation and ensure the code saved.
Step 5: Create an HTTP Trigger
- In the function’s Triggers section, choose Create Trigger.
- Select HTTP Trigger.
- Configure (names vary slightly by console):
– Auth type: choose a mode that allows easy testing (often “Anonymous” for a lab).
For production, prefer an authenticated mode and add your own auth checks. – Methods:GET(and optionallyPOST) – Path:/(or a simple route) - Create the trigger.
- Copy the generated Invoke URL (endpoint).
Expected outcome: An HTTP endpoint is created that routes requests to your function.
Verification – Trigger appears in the function trigger list. – Invoke URL is shown.
Common errors and fixes – 403 Forbidden: Your trigger may require authentication; re-check auth mode or use signed requests if required by your configuration. – 404 Not Found: Ensure you’re using the correct invoke URL and path.
Step 6: Invoke the function from your terminal
Use curl from a machine with internet access:
curl -sS -X GET "https://YOUR_INVOKE_URL_HERE" | python3 -m json.tool
If python3 is not available, just run:
curl -sS -X GET "https://YOUR_INVOKE_URL_HERE"
Expected outcome: You receive a JSON response similar to:
{
"ok": true,
"app": "fc-http-lab",
"stage": "dev",
"note": "Hello from Alibaba Cloud Function Compute"
}
Verification – Response is HTTP 200 (or success status depending on trigger). – Response JSON contains your environment variable values.
Step 7: Validate logs in Log Service (SLS)
- Open Log Service (SLS) console.
- Navigate to your project and logstore configured for the service.
- Search recent logs.
You should see a JSON log line similar to:
{"ts":"2026-04-12T00:00:00Z","app":"fc-http-lab","stage":"dev","message":"Function invoked"}
Expected outcome: Logs are visible for each invocation.
Verification
– Each curl call results in a new log entry.
– Timestamp and fields match your output.
Common errors and fixes – No logs appear: – Confirm the service logging configuration points to the correct SLS project/logstore. – Confirm the service execution role has SLS write permissions. – Wait 1–2 minutes; some pipelines have slight delay.
Step 8: (Optional) Publish a version and create an alias
For production-style releases, use versions and aliases.
- In Function Compute, publish a Version of the service/function.
- Create an Alias named
prodpointing to that version. - If your trigger supports binding to an alias/version, update the trigger to invoke through
prod(console behavior varies—verify in docs for your trigger type).
Expected outcome: You have a stable alias that can be updated to roll forward/back.
Verification – Alias exists and points to a specific version. – Invocations go through the alias if configured.
Validation
Use this checklist: – [ ] HTTP endpoint returns JSON – [ ] Environment variables appear in output – [ ] Logs appear in SLS for each invocation – [ ] No unexpected timeouts or permission errors
Troubleshooting
Issue: 403 Forbidden on invoke – Cause: Trigger requires authentication. – Fix: – For the lab, switch auth to an open mode (if permitted). – For production, implement request signing/authorization and keep endpoint protected.
Issue: Function timeouts – Cause: Network calls blocked or DNS issues; VPC/NAT misconfiguration if VPC is enabled. – Fix: – Keep VPC disabled for the first lab. – If using VPC, ensure NAT Gateway and route tables allow egress.
Issue: Logs not showing in SLS – Cause: Missing SLS permissions or misconfigured project/logstore. – Fix: – Check service logging settings. – Verify RAM role permissions for SLS write. – Confirm you are in the correct region and logstore.
Issue: “Handler not found”
– Cause: Incorrect handler string or file name.
– Fix:
– Ensure index.py exists and handler is index.handler.
Cleanup
To avoid ongoing charges:
1. Delete the HTTP trigger.
2. Delete the function hello-http.
3. Delete the service fc-http-tutorial-service.
4. In Log Service, delete the logstore (and project if it was created solely for this lab).
5. If you created a dedicated RAM role for the lab, delete it (only if not used elsewhere).
Expected outcome: No remaining resources from the lab.
11. Best Practices
Architecture best practices
- Use Function Compute for event-driven and bursty components; keep long-running services in containers/VMs.
- Prefer asynchronous patterns (EventBridge/queue) for heavy workloads; keep HTTP functions fast.
- Design idempotent handlers to tolerate retries and duplicate events.
- Apply backpressure: limit concurrency and use queues to protect databases.
IAM/security best practices
- Use RAM roles for function execution; avoid embedding AccessKey/Secret in code.
- Grant least privilege: separate roles per service or per application domain.
- Restrict who can update function code and triggers; treat deploy rights as production access.
- Use resource-level permissions where supported (function/service ARNs/resources).
Cost best practices
- Right-size memory using measurement (duration vs memory).
- Keep logs lean; avoid logging full request bodies in production.
- Set SLS retention and indexing policies intentionally.
- Avoid unnecessary VPC egress through NAT; use internal endpoints where possible.
Performance best practices
- Keep dependencies minimal to reduce cold start.
- Reuse connections (HTTP keep-alive, DB connection pools) when runtime reuse is available; still handle reconnects safely.
- Use provisioned/pre-warmed capacity only for latency-sensitive endpoints (verify feature and billing).
Reliability best practices
- Implement retries with exponential backoff on transient downstream errors.
- Add timeouts to outbound calls; avoid hanging requests.
- Use DLQ or failure destinations if supported for async events (verify in docs).
- Use versions/aliases for safe rollouts and quick rollback.
Operations best practices
- Standardize naming:
{app}-{env}-{component}. - Tag resources for cost and ownership.
- Set CloudMonitor alarms on error rate, throttles, and duration.
- Create runbooks for common failures (timeouts, permission errors, dependency outages).
Governance/tagging/naming best practices
- Enforce an ownership tag (team name/email).
- Separate environments (dev/stage/prod) by account or at minimum by naming and RAM boundaries.
- Require code review for IAM changes and trigger exposure changes.
12. Security Considerations
Identity and access model
- RAM users/roles control who can:
- Create/update functions and triggers
- View logs and configuration
- Invoke functions (depending on trigger type)
- Execution role (RAM role attached to the service/function) controls what the function can access.
Recommendation: Create separate roles:
– fc-exec-role-dev (broader permissions for development)
– fc-exec-role-prod (least privilege for production)
Encryption
- Data in transit: use HTTPS for HTTP triggers and service-to-service calls.
- Data at rest: logs in SLS and objects in OSS support encryption options; configure according to your compliance needs.
- For secrets, prefer a managed secret service or KMS-based encryption pattern (verify Alibaba Cloud’s current secret management services and recommended integration patterns).
Network exposure
- Avoid anonymous/public endpoints for production unless absolutely required.
- Use authentication at the edge (API Gateway, WAF) or enforce application-level auth.
- For private resources, attach functions to VPC and keep databases non-public.
Secrets handling
Common mistakes: – Storing AccessKey/Secret in code repositories – Putting secrets directly in environment variables without access control – Logging secrets accidentally
Better approaches: – Use RAM roles for Alibaba Cloud API access. – Store secrets in a managed secrets solution and fetch at runtime with caching (verify the official recommended service). – Rotate credentials and set alerts for suspicious access.
Audit/logging
- Use ActionTrail (or your organization’s audit tooling) to track administrative actions (verify configuration).
- Log deployment actions and changes to triggers.
- Keep a change history: versions/aliases plus CI/CD logs.
Compliance considerations
- Ensure region selection meets data residency requirements.
- Define retention policies for logs (SLS) and enforce them.
- Apply separation of duties: deployers vs approvers for production changes.
Secure deployment recommendations
- Place HTTP endpoints behind API Gateway/WAF for consistent auth, throttling, and IP allowlisting (if required).
- Use private connectivity for data services.
- Apply least privilege to execution role, and restrict who can modify that role.
- Use versions/aliases for controlled releases.
13. Limitations and Gotchas
Verify exact limits in the official Function Compute docs for your region.
Known limitations / common constraints
- Timeout limits: Functions have a maximum execution time; not suitable for long-running jobs.
- Cold starts: Infrequently invoked functions may have higher latency on the first request.
- Package size limits: Large dependencies can hit deployment limits or increase cold start.
- Ephemeral filesystem: Local disk is temporary; persist data in OSS/NAS/databases.
- Concurrency burst behavior: Sudden spikes can overwhelm downstream services if you don’t add limits/queues.
Regional constraints
- Available runtimes, triggers, and advanced features may differ by region.
- Some integrations might require resources in the same region.
Pricing surprises
- High log volume in SLS (especially indexed logs).
- NAT Gateway charges when VPC-attached functions call the internet.
- Retries causing multiplied invocations.
Compatibility issues
- Native libraries may require a compatible runtime environment; container-based deployment can help.
- Timezone/locale assumptions; always log in UTC and handle localization explicitly.
Operational gotchas
- Changing trigger auth modes can unintentionally expose endpoints.
- Overly broad RAM roles for execution can become a lateral movement risk.
- Lack of idempotency leads to duplicated side effects on retries.
Migration challenges
- Porting a monolith directly to functions usually fails; refactor into event-driven components.
- State management needs redesign (externalize state).
- Observability requires structured logging and correlation IDs from day one.
Vendor-specific nuances (Alibaba Cloud)
- Service/function configuration hierarchy matters (service-level role/logging/VPC).
- Tooling evolves (for example, older Funcraft tutorials vs newer Serverless Devs). Follow current official guidance.
14. Comparison with Alternatives
Within Alibaba Cloud
- ECS (Elastic Compute Service): Full VM control, best for long-running services.
- ACK (Alibaba Cloud Container Service for Kubernetes): Container orchestration for microservices/platform workloads.
- SAE (Serverless App Engine): Higher-level serverless for applications (more “app platform” than FaaS).
- ECI (Elastic Container Instance): Run containers without managing VMs; good for batch/container workloads.
Other clouds (nearest equivalents)
- AWS Lambda
- Azure Functions
- Google Cloud Functions / Cloud Run (for container-based serverless)
Open-source / self-managed alternatives
- Knative (Kubernetes-based serverless)
- OpenFaaS
- Apache OpenWhisk
Comparison table
| Option | Best For | Strengths | Weaknesses | When to Choose |
|---|---|---|---|---|
| Alibaba Cloud Function Compute | Event-driven functions on Alibaba Cloud | Deep Alibaba Cloud integration, autoscaling, pay-per-use | Limits on runtime/time/package; cold starts | You want FaaS tightly integrated with Alibaba Cloud services |
| Alibaba Cloud SAE | Deploying apps without managing servers | App-centric workflows, less function plumbing | Less granular than functions; may not fit event-trigger patterns | You have a web app/service and want serverless operations |
| Alibaba Cloud ACK | Complex microservices platforms | Full Kubernetes ecosystem and control | Operational overhead and cost; needs SRE maturity | You need Kubernetes portability and long-running services |
| Alibaba Cloud ECS | Full control workloads | Predictable environment, broad compatibility | You manage scaling/patching/cost of idle | You need OS control or long-running processes |
| AWS Lambda | Serverless functions on AWS | Mature ecosystem and tooling | Different IAM/networking model; cloud lock-in | You’re primarily on AWS |
| Azure Functions | Serverless on Azure | Strong Microsoft ecosystem integration | Different dev model; pricing/limits vary | You’re primarily on Azure |
| Knative/OpenFaaS | Self-managed serverless | Portability, control | You operate Kubernetes and the platform | You need on-prem/hybrid control and accept ops overhead |
15. Real-World Example
Enterprise example: Security event enrichment and automated response
- Problem: A security team receives high-volume alerts (WAF, IDS, IAM anomalies). Manual triage is slow, and alerts lack context.
- Proposed architecture
- Event sources (WAF logs, cloud audit events) route into Log Service (SLS) and/or EventBridge.
- A Function Compute function enriches events (asset owner, severity, geo-IP, historical context).
- Enriched events are written back to SLS and forwarded to an incident workflow system.
- Concurrency is limited to protect downstream CMDB and ticketing APIs.
- Why Function Compute was chosen
- Event-driven scaling handles spikes during incidents.
- RAM roles allow controlled access to internal APIs.
- SLS integration provides search and audit-friendly logs.
- Expected outcomes
- Faster mean-time-to-detect (MTTD) and mean-time-to-respond (MTTR)
- Consistent enrichment logic across teams
- Lower cost vs always-on worker fleets
Startup/small-team example: Serverless webhook + async processing
- Problem: A startup integrates multiple partners sending webhooks. Traffic is unpredictable; they want low ops overhead.
- Proposed architecture
- HTTP trigger receives webhooks in Function Compute.
- The function validates signatures and enqueues events (via an Alibaba Cloud messaging service or EventBridge—verify your choice).
- A worker function processes events asynchronously (normalize payloads, call internal APIs).
- Logs and metrics go to SLS/CloudMonitor.
- Why Function Compute was chosen
- Minimal infrastructure to manage.
- Pay only for usage, which matches early-stage traffic patterns.
- Fast to iterate as partners change formats.
- Expected outcomes
- Rapid onboarding of partners
- Reduced operational burden (no servers)
- Controlled scaling with queue buffering
16. FAQ
1) Is Function Compute the same as AWS Lambda?
They are similar concepts (FaaS), but they are different products with different IAM models, triggers, tooling, and pricing. Use Alibaba Cloud docs and console workflows specifically for Function Compute.
2) Do I need a VPC to use Function Compute?
No. Use VPC only when you must access private resources (private RDS/Redis/internal services). For simple public HTTP endpoints, you can start without VPC.
3) How do I secure an HTTP-triggered function?
Prefer authenticated trigger modes, API Gateway/WAF, request signing, and application-level authorization checks. Avoid anonymous public endpoints for production.
4) What causes cold starts and how do I reduce them?
Cold starts occur when the platform needs to initialize a new execution environment. Reduce by minimizing package size and initialization work, and consider provisioned/pre-warmed capacity if supported (verify feature availability and cost).
5) Can functions access other Alibaba Cloud services without AccessKeys?
Yes—use a RAM execution role attached to the service/function. This is the preferred approach.
6) Where do my function logs go?
Commonly to Log Service (SLS) when logging is enabled in the service configuration.
7) How do I troubleshoot timeouts to external APIs?
If using VPC, ensure NAT and routing are configured. Also set client-side timeouts and verify DNS/network access.
8) How do retries work for event triggers?
Retry behavior is trigger-specific. Verify delivery semantics (at-least-once vs best-effort), retry counts, and DLQ options in official docs for your trigger type.
9) Can I run long batch jobs in Function Compute?
Function Compute is not designed for long-running jobs beyond the platform timeout limit. For long batch jobs, consider ECI, ACK, or compute services designed for batch.
10) How do I deploy functions with CI/CD?
Use official tooling (often Serverless Devs) or the Function Compute API. Use versions/aliases for safe promotion. Verify current best practices in official docs.
11) How do I manage dependencies?
Use the platform’s supported packaging approach (zip/package, layers if supported, or container images). Keep dependencies small and pinned.
12) What is the difference between a service and a function?
A service is a container for shared config (role/VPC/logging). A function is the executable code unit with runtime and resource settings.
13) Can I connect Function Compute to a private database?
Yes, by enabling VPC integration and ensuring the database is reachable via VPC networking/security group rules.
14) How do I control costs?
Reduce invocation count, right-size memory, minimize duration, control logging volume, and avoid unnecessary NAT egress. Use the pricing calculator.
15) How do I do blue/green or canary deployments?
Use versions and aliases and route traffic via aliases where supported. Verify how your trigger binds to versions/aliases in your region.
16) What observability should I set up for production?
At minimum: SLS logs with structured logging, CloudMonitor alarms (errors, duration, throttles), and correlation IDs. Add tracing if your org uses ARMS or OpenTelemetry (verify supported integrations).
17. Top Online Resources to Learn Function Compute
| Resource Type | Name | Why It Is Useful |
|---|---|---|
| Official documentation | Function Compute Documentation (Alibaba Cloud Help Center): https://www.alibabacloud.com/help/en/function-compute/ | Canonical reference for concepts, triggers, runtimes, limits, and APIs |
| Official product page | Function Compute product page: https://www.alibabacloud.com/product/function-compute | Overview, key capabilities, and entry points |
| Official pricing | Function Compute Pricing: https://www.alibabacloud.com/product/function-compute/pricing | Current billing model and region-specific pricing |
| Pricing calculator | Alibaba Cloud Pricing Calculator: https://www.alibabacloud.com/pricing/calculator | Build estimates using your invocation/duration assumptions |
| Developer tooling | Serverless Devs: https://www.serverless-devs.com/ | Commonly recommended toolchain for building/deploying serverless apps on Alibaba Cloud |
| Official/maintained code (tooling) | Serverless Devs GitHub: https://github.com/Serverless-Devs/Serverless-Devs | Source, templates, and issues—useful for real-world deployment patterns |
| Legacy tooling (reference) | Funcraft (legacy; verify current status): https://github.com/aliyun/fun | Useful for understanding older projects; prefer current official tooling guidance |
| Observability | Log Service (SLS) Documentation: https://www.alibabacloud.com/help/en/sls/ | Essential for logging, search, dashboards, alerting, and retention |
| IAM | RAM Documentation: https://www.alibabacloud.com/help/en/ram/ | Learn least privilege policies and role-based access for Function Compute |
| Eventing | EventBridge Documentation: https://www.alibabacloud.com/help/en/eventbridge/ | Event routing patterns that commonly pair with Function Compute |
18. Training and Certification Providers
| Institute | Suitable Audience | Likely Learning Focus | Mode | Website URL |
|---|---|---|---|---|
| DevOpsSchool.com | DevOps engineers, SREs, platform teams, cloud beginners | DevOps + cloud fundamentals, CI/CD, cloud-native patterns (verify current catalog) | check website | https://www.devopsschool.com/ |
| ScmGalaxy.com | Students, junior engineers, SCM/DevOps learners | SCM, DevOps tooling, automation basics (verify current catalog) | check website | https://www.scmgalaxy.com/ |
| CLoudOpsNow.in | Cloud operations learners, sysadmins moving to cloud | Cloud operations, monitoring, cost basics (verify current catalog) | check website | https://www.cloudopsnow.in/ |
| SreSchool.com | SREs, reliability-focused engineers | Reliability engineering, monitoring/alerting, incident response (verify current catalog) | check website | https://www.sreschool.com/ |
| AiOpsSchool.com | Ops teams exploring AIOps | AIOps fundamentals, automation, observability (verify current catalog) | check website | https://www.aiopsschool.com/ |
19. Top Trainers
| Platform/Site | Likely Specialization | Suitable Audience | Website URL |
|---|---|---|---|
| RajeshKumar.xyz | DevOps/cloud training content (verify specific offerings) | Beginners to intermediate engineers | https://rajeshkumar.xyz/ |
| devopstrainer.in | DevOps training and mentoring (verify catalog) | Engineers seeking hands-on DevOps skills | https://www.devopstrainer.in/ |
| devopsfreelancer.com | Freelance DevOps help/training platform (verify services) | Small teams needing practical guidance | https://www.devopsfreelancer.com/ |
| devopssupport.in | DevOps support and learning resources (verify services) | Ops/DevOps teams needing troubleshooting support | https://www.devopssupport.in/ |
20. Top Consulting Companies
| Company Name | Likely Service Area | Where They May Help | Consulting Use Case Examples | Website URL |
|---|---|---|---|---|
| cotocus.com | Cloud/DevOps consulting (verify service lines) | Cloud architecture, DevOps pipelines, operations | Serverless adoption planning; CI/CD setup; logging/monitoring strategy | https://cotocus.com/ |
| DevOpsSchool.com | DevOps consulting and training (verify offerings) | DevOps transformation, platform engineering practices | Build deployment pipelines for Function Compute; implement IaC and governance | https://www.devopsschool.com/ |
| DEVOPSCONSULTING.IN | DevOps consulting (verify service lines) | Automation, CI/CD, reliability improvements | Production readiness reviews; cost and security reviews for serverless workloads | https://www.devopsconsulting.in/ |
21. Career and Learning Roadmap
What to learn before Function Compute
- Basic cloud concepts: regions, IAM, networking, billing.
- HTTP fundamentals: requests, headers, auth, REST basics.
- One programming language runtime you’ll use (Python/Node.js/Java).
- Logging and monitoring basics.
- Basic security hygiene: least privilege, secrets, encryption.
What to learn after Function Compute
- Event-driven architecture patterns (queues, event buses, idempotency).
- VPC networking patterns for serverless (private endpoints, NAT, DNS).
- CI/CD for serverless (artifact versioning, staged deployments).
- Observability maturity: dashboards, alerting, tracing, SLOs.
- Cost optimization practices and chargeback/showback.
Job roles that use it
- Cloud engineer / Solutions engineer
- DevOps engineer / SRE
- Backend engineer building APIs and integrations
- Platform engineer building internal automation platforms
- Security engineer building automation and response workflows
Certification path (if available)
Alibaba Cloud certification programs change over time. Check Alibaba Cloud’s official certification pages for current tracks and whether Function Compute appears in the exam objectives.
Project ideas for practice
- Build a webhook receiver + async worker pipeline with retries and idempotency.
- Create an OSS-triggered image pipeline (thumbnails + metadata).
- Implement scheduled cost reporting using CloudMonitor metrics and function emails/notifications.
- Build a multi-environment deployment using versions/aliases and automated rollback.
- Create a private VPC-connected function that queries a private RDS and exposes a secured API.
22. Glossary
- Serverless: A cloud model where the provider manages infrastructure; you deploy code and pay primarily for usage.
- FaaS (Functions as a Service): Serverless functions executed on demand in response to events.
- Function: The code unit executed by Function Compute, with a runtime and configuration.
- Service (Function Compute): A container for functions that shares common configuration (role, VPC, logging).
- Trigger: A configuration that connects an event source (HTTP, timer, OSS, etc.) to a function.
- Invocation: A single execution of a function.
- Cold start: Extra latency when a new execution environment must be initialized.
- Concurrency: The number of function instances executing simultaneously.
- RAM (Resource Access Management): Alibaba Cloud identity and access management.
- Execution role: A RAM role assumed by the function at runtime to call Alibaba Cloud APIs.
- SLS (Log Service): Alibaba Cloud logging service for storing, querying, and alerting on logs.
- CloudMonitor: Alibaba Cloud monitoring service for metrics and alarms.
- VPC: Virtual Private Cloud; private network boundary for resources.
- NAT Gateway: Enables outbound internet access from private networks.
- Version: An immutable snapshot of function/service configuration and code at publish time.
- Alias: A stable pointer to a version, used for releases and rollbacks.
- Idempotency: Property of an operation that can be repeated without causing additional side effects.
23. Summary
Alibaba Cloud Function Compute is a regional serverless (FaaS) service that runs code on demand in response to events like HTTP requests and scheduled triggers, integrating tightly with Alibaba Cloud IAM (RAM), networking (VPC), and observability (SLS/CloudMonitor).
It matters because it reduces infrastructure operations, scales automatically, and aligns cost with real usage—especially for bursty APIs, webhooks, automation, and event processing. The main cost and reliability considerations are execution duration/memory sizing, log volume in SLS, NAT/data egress, retry behavior, and cold-start sensitivity. Security success depends on least-privilege RAM roles, secure endpoint exposure, and a strong secrets strategy.
Use Function Compute when you want event-driven components with minimal ops overhead. Prefer containers/VMs when you need long-running processes, deep OS control, or strict ultra-low-latency without serverless tradeoffs.
Next step: read the official Function Compute docs, then extend the lab into a production-style design using versions/aliases, stricter RAM policies, and (if needed) VPC connectivity to private data services.