---
term: 'Cloud Code (Serverless Functions)'
seoTitle: 'Cloud Code & Serverless Functions: FaaS, Triggers, Cold Starts'
headline: 'What is Cloud Code (Serverless Functions)?'
slug: cloud-code-serverless-functions
category: backend-compute
shortDefinition: 'Cloud Code is a serverless model where backend logic runs as server-side functions triggered by calls, data events, or schedules.'
relatedTerms:
  - serverless-architecture
  - baas-vs-serverless
  - iaas-paas-baas-faas
  - webhooks
contrastsWith:
  - edge-computing-edge-functions
aboutTerms:
  - 'FaaS (Functions-as-a-Service)'
  - 'Cloud Functions'
  - 'Function Triggers'
faq:
  - question: 'What is a serverless function?'
    answer: 'A small, single-purpose block of server-side code that a platform runs on demand in response to an event — an HTTP call, a data change, a schedule — with the provider handling provisioning, scaling, and maintenance. You deploy logic; the platform owns the machinery that executes it.'
  - question: 'Are serverless functions really serverless?'
    answer: 'No — servers exist; they are simply not your problem. "Serverless" describes the developer experience: no machines to provision, patch, or scale. The provider spins execution environments up and down invisibly, including down to zero when nothing is running.'
  - question: 'What is the difference between FaaS and serverless?'
    answer: 'FaaS — Functions-as-a-Service — is the compute half of serverless: individual functions triggered by events. Serverless is the broader model that also includes managed backend services (database, auth, storage — the BaaS half). Cloud Code is the point where the two halves meet: functions running with a managed backend.'
  - question: 'How are serverless functions triggered?'
    answer: 'Five families: direct calls (a client or API invokes the function by name), database events (code that runs before or after saves and deletes), auth events (hooks on login and signup), schedules (cron-style jobs), and incoming webhooks from external systems. A good platform exposes all five as registration, not infrastructure.'
  - question: 'What is a cold start?'
    answer: 'The latency — hundreds of milliseconds to seconds — when a platform must initialize a fresh execution environment for a function that had scaled to zero. Mitigations include minimum warm instances and smaller bundles; functions hosted on an always-running backend sidestep the scale-from-zero case entirely.'
  - question: 'Why must serverless functions be stateless?'
    answer: 'Because any of many parallel, short-lived instances may serve the next request — memory held between invocations is a bug waiting to vanish. Persistent state belongs in a database or cache. In the BaaS variant the database is already attached, which is much of the model''s convenience.'
  - question: 'What are the limits of serverless functions?'
    answer: 'Platforms cap execution time (seconds by default, several minutes at most), memory, and payload sizes — long-running work belongs in background jobs, and sustained heavy throughput can cost more than an always-on server. The limits are the price of per-request scaling.'
  - question: 'What is the difference between serverless functions and microservices?'
    answer: 'Different axes: microservices are an architectural decomposition; serverless is an execution model. A function is finer-grained than a microservice, and a microservice may be implemented as functions, containers, or a monolith slice. Containers buy control and long-lived processes; functions buy zero operations and per-request scale.'
  - question: 'Do serverless functions cause vendor lock-in?'
    answer: 'Proprietary event formats and tooling create real coupling on closed platforms. The counterweight is open source: functions written against open runtimes — including Back4app''s open-source Cloud Code, which runs on any Node.js host — move with your backend rather than binding you to one cloud''s eventing.'
codeLanguages: [javascript, dart, swift, kotlin]
externalAuthorities:
  - name: 'Serverless Architectures — Martin Fowler'
    url: 'https://martinfowler.com/articles/serverless.html'
  - name: 'CNCF Serverless Whitepaper'
    url: 'https://github.com/cncf/wg-serverless/tree/master/whitepapers/serverless-overview'
  - name: 'Cloud Code guide'
    url: 'https://docs.parseplatform.org/cloudcode/guide/'
  - name: 'OpenFaaS — open-source functions'
    url: 'https://www.openfaas.com/'
  - name: 'Function as a service — Wikipedia'
    url: 'https://en.wikipedia.org/wiki/Function_as_a_service'
cta:
  title: 'Functions that live with your backend'
  text: 'Back4app Cloud Code runs your JavaScript next to your database, auth, and files — callable functions, save triggers, and scheduled jobs in one deploy, no servers and no cold-start tax.'
  linkText: 'Start building free'
  linkUrl: 'https://www.back4app.com/signup'
author: 'Back4app Engineering'
publishedDate: '2026-07-30'
translationKey: cloud-code-serverless-functions
---

**Cloud Code is a serverless model where backend logic runs as server-side functions triggered by calls, data events, or schedules.** Two clarifications up front, because the term family is muddled. First, "serverless" means the servers are *someone else's problem* — they exist, invisibly, scaled for you. Second, functions come in two architectures: standalone **FaaS**, where each function is an isolated unit wired to external services, and the **BaaS variant** this article is named for — functions deployed *into* your backend, sharing an environment with the database, auth, and files they act on.

## Key takeaways

| Question | Answer |
| --- | --- |
| The four properties | Event-triggered · stateless · auto-scaling · pay-per-use |
| The two flavors | Standalone FaaS units vs. Cloud Code living with your backend |
| The trigger families | Called by name · data events · auth events · schedules · webhooks |
| Why server-side | Clients can be decompiled; functions can't be tampered with |
| The honest limits | Timeouts, statelessness, and cold starts (where scale-to-zero applies) |

## One function, called from everywhere

The classic aggregation example — compute next to the data, ship only the answer:

**JavaScript:**

```javascript
// JavaScript / Node.js — Back4app JS SDK
// Calling a Cloud Code function: server-side logic, one line from the client
const avg = await Parse.Cloud.run('averageStars', { movie: 'Arrival' });
// The aggregation ran NEXT TO the database — only the answer crossed the wire

// The function itself (cloud/main.js — deployed to your backend, not the app):
// Parse.Cloud.define('averageStars', async (req) => {
//   const q = new Parse.Query('Review').equalTo('movie', req.params.movie);
//   const reviews = await q.find({ useMasterKey: true });
//   return reviews.reduce((s, r) => s + r.get('stars'), 0) / reviews.length;
// });
```

**Flutter:**

```dart
// Flutter / Dart — Back4app Flutter SDK
// Calling a Cloud Code function: server-side logic, one line from the client
final response = await ParseCloudFunction('averageStars')
    .execute(parameters: {'movie': 'Arrival'});
final avg = response.result;
// The aggregation ran NEXT TO the database — only the answer crossed the wire
// The function lives in cloud/main.js on your backend — update it anytime;
// every client gets the new logic instantly, no app-store release required.
```

**Swift:**

```swift
// iOS / Swift — Back4app Swift SDK
// Calling a Cloud Code function: server-side logic, one line from the client
let avg: Double = try await Cloud.run(name: "averageStars",
                                      parameters: ["movie": "Arrival"])
// The aggregation ran NEXT TO the database — only the answer crossed the wire
// The function lives in cloud/main.js on your backend — update it anytime;
// every client gets the new logic instantly, no app-store release required.
```

**Kotlin:**

```kotlin
// Android / Kotlin — Back4app Android SDK
// Calling a Cloud Code function: server-side logic, one line from the client
val params = mapOf("movie" to "Arrival")
val avg = ParseCloud.callFunction<Double>("averageStars", params)
// The aggregation ran NEXT TO the database — only the answer crossed the wire
// The function lives in cloud/main.js on your backend — update it anytime;
// every client gets the new logic instantly, no app-store release required.
```

Averaging a thousand reviews on the phone means downloading a thousand reviews; the function version moves one number. That bandwidth argument generalizes into the whole case for server-side logic below.

## The trigger taxonomy

Ranking explainers list triggers in a sentence; the structure deserves a table:

| Trigger family | Fires when | Canonical use |
| --- | --- | --- |
| Callable functions | A client invokes by name with JSON params | Business logic, aggregations, actions |
| Data triggers | Before/after save, delete, find on a class | Validation, defaults, cascades, audit |
| Auth triggers | Before login, after signup/logout | Blocklists, welcome flows, audit events |
| Scheduled jobs | Cron expressions | Reports, cleanups, TTL sweeps, digests |
| Incoming [webhooks](/glossary/webhooks/) | An external system POSTs an event | Payment confirmations, CI notifications |

```mermaid
flowchart LR
  accTitle: Event sources triggering serverless functions beside a managed backend
  accDescr: Client calls, database save events, authentication events, cron schedules, and external webhooks all trigger server-side functions, which read and write the managed database, call external APIs with server-held secrets, and return results, with the platform scaling execution automatically.
  C["Client call<br/>by name"] --> F["Function<br/>(your logic, managed runtime)"]
  D["Data event<br/>before/after save"] --> F
  A["Auth event<br/>login, signup"] --> F
  S["Schedule<br/>cron"] --> F
  W["External webhook"] --> F
  F --> DB[("Managed database<br/>ACLs enforced")]
  F -->|"secrets stay server-side"| X["Third-party APIs"]
```

## Why logic belongs server-side

Four arguments, each missing from most explainers. **Don't trust the client:** apps are decompiled and requests are forged; price calculations, permission checks, and game scores computed on-device are suggestions, while the same logic in a function is law — a `beforeSave` trigger validates every write regardless of which client sent it. **Secrets stay home:** third-party API keys live in the function's environment, never in a bundle anyone can unpack — the [API-key discipline](/glossary/api-key-security/) made structural. **Update without release:** server logic changes deploy instantly to every user, with no app-store review cycle between the fix and the fixed. **Compute near data:** aggregation, search shaping, and fan-out run microseconds from the database instead of across a mobile network.

## Cloud Code vs. standalone FaaS vs. containers

| | Cloud Code (BaaS functions) | Standalone FaaS | Containers |
| --- | --- | --- | --- |
| Runs | Inside your backend's runtime | Isolated per-function units | Wherever you orchestrate them |
| Context | Database, auth, ACLs already attached | Every service wired manually | Whatever you build in |
| Deploy unit | One codebase, one deploy | Per function | Per image |
| Cold starts | None — the backend is already up | Yes, on scale-from-zero | Only if you scale to zero |
| Privileged ops | Master-key access for admin logic | Per-function IAM wiring | Your own auth fabric |
| Scaling | With the backend | Per request, to zero | As configured |
| Fits | App backends on a BaaS | Spiky, isolated event work | Long-running, stateful services |

The [serverless architecture](/glossary/serverless-architecture/) entry covers the model broadly and [FaaS's place in the service ladder](/glossary/iaas-paas-baas-faas/) has its own article; the row that matters here is *context*: Cloud Code functions are born connected — the same SDK, the same session semantics, ACLs enforced on their queries — where standalone FaaS starts every project with plumbing.

## Cold starts and statelessness, honestly

Two properties follow from per-request scaling, and both deserve plain statement. **Cold starts** happen when a scaled-to-zero function must initialize an environment before running — hundreds of milliseconds to seconds on typical platforms, mitigated by warm minimum instances and lean bundles, and *architecturally absent* for functions hosted on an always-running backend, which is a genuine difference between the two flavors rather than a vendor boast. **Statelessness** means nothing in memory survives between invocations by contract: counters, caches, and sessions held in a function are bugs on a timer. State goes to the database — and the BaaS variant's quiet advantage is that the database is one line away rather than a service you must select, connect, and secure first.

## Common use cases

- **Validation and business rules** — `beforeSave` gates that make invariants non-negotiable across every client.
- **Aggregations and reports** — compute beside the data; return answers, not datasets.
- **Third-party integration** — payments, email, AI APIs called with server-held secrets.
- **[Webhook](/glossary/webhooks/) receivers and emitters** — functions as the HTTP faces of event integrations.
- **Scheduled maintenance** — digests, cleanups, and sweeps on cron, no worker fleet to run.

## Should it be a function? A decision matrix

| Work | Home |
| --- | --- |
| Logic clients could tamper with | Function — always |
| Spiky, event-shaped tasks | Function |
| Long-running computation (minutes+) | Background job, not a function |
| Stateful, always-on services (sockets, queues) | Containers / platform services |
| Latency-critical hot path at huge sustained volume | Measure — always-on may win |
| Everything touching a secret | Function — the secret never ships |

## Limitations and trade-offs

- **Timeouts are contracts.** Functions are capped at seconds-to-minutes; work that might exceed the cap needs a job queue, not hope.
- **Statelessness is strict.** In-memory anything is ephemeral; designs that forget this pass tests and fail under scale-out.
- **Sprawl is the failure mode.** Fifty small functions without shared modules and naming discipline become a distributed monolith with worse tooling.
- **Debugging is remote by nature.** Logs and traces replace breakpoints; platforms with good log surfaces earn their keep here.
- **Cost inverts at sustained load.** Pay-per-use is unbeatable for spiky work and beatable by always-on servers at constant high throughput — price the curve, not the brochure.

## Cloud Code on Back4app

Back4app is an open-source Backend-as-a-Service (BaaS) platform that combines a managed database, auto-generated REST and GraphQL APIs, authentication, file storage, and Cloud Code serverless functions. Cloud Code here is the BaaS flavor in its original form: JavaScript deployed into your Back4app backend — `Parse.Cloud.define` for callable functions like the code tabs' example, `beforeSave`/`afterSave` triggers for data rules, auth hooks, and scheduled jobs, all in one codebase and one deploy. Functions run with context attached: the same SDK your clients use, ACLs and [class-level permissions](/glossary/class-level-permissions-clp/) enforced on queries, master-key access available when admin logic legitimately needs to bypass them, and secrets in server-side configuration. Because the backend is always running, the scale-from-zero cold start never applies — and because the platform is open source, the functions are portable to any host that runs it, which is the practical answer to the lock-in question.
