Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 35 ยท App Platform and Functions

DigitalOcean Functions: Serverless Code Without Servers

Write and deploy serverless functions on DigitalOcean: namespaces, packages, the main entry point, web and scheduled triggers, doctl serverless, limits, cold starts and billing in GiB-seconds.

Functions is DigitalOcean's serverless compute service. You write a small piece of code, deploy it, and DigitalOcean runs it only when something triggers it: an HTTP request, a schedule, or a call from another system. There are no servers to size, and you pay for execution rather than for idle time. It is a great fit for webhooks, form handlers, small APIs, image or file processing steps and scheduled clean-ups.

Functions are built on the open-source Apache OpenWhisk platform and support runtimes such as Node.js, Python, Go and PHP. Check the current list with doctl serverless commands, as versions change.

You cannot deploy to DigitalOcean from this site, so deployment commands are read-only. The Python function in this lesson is plain Python: the runnable demos call it locally with a tiny stand-in invoker, which mirrors how the platform calls your code.

Core concepts

  • Namespace: a container for your functions in one region, created automatically when you connect doctl. It has its own access credentials.
  • Package: a folder grouping related functions, for example shop.
  • Action (function): the code unit. Its entry point is a function called main that receives arguments and returns a result.
  • Trigger: what starts it. A web function has a public URL; a scheduled trigger uses a cron expression; you can also invoke it by name from the CLI or the API.
  • Activation: one execution, with logs, duration and result you can look up later.
flowchart LR
  W["HTTPS request"] --> F["Function: main(args)"]
  C["Cron trigger"] --> F
  A["API / doctl invoke"] --> F
  F --> R["Result JSON / HTTP response"]
  F --> L["Activation log"]

Several triggers can start the same code; each run is an activation.

Project layout

doctl scaffolds the structure for you:

TEXT
my-functions/
  project.yml
  packages/
    shop/
      hello/
        hello.py
      thumbs/
        index.js

project.yml declares packages, functions, their runtime, web exposure and limits:

YAML
packages:
  - name: shop
    functions:
      - name: hello
        runtime: python:default
        web: true
        limits:
          timeout: 10000      # milliseconds
          memory: 256         # megabytes
        environment:
          GREETING: Hello
        triggers:
          - name: every-morning
            sourceType: scheduler
            sourceDetails:
              cron: "0 7 * * *"

A first function

A Python function named main takes a dictionary and returns a dictionary. For a web function, the returned dictionary can contain statusCode, headers and body, and query parameters or the JSON body arrive merged into the arguments.

Python
# packages/shop/hello/hello.py
import os

def main(args):
    name = args.get("name", "world")
    greeting = os.environ.get("GREETING", "Hello")
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": {"message": f"{greeting}, {name}!"},
    }

Deploy and call it:

Terminal
doctl serverless install                 # one-time: installs the serverless support
doctl serverless connect                 # connect to your namespace
doctl serverless init --language python my-functions
cd my-functions
doctl serverless deploy .
doctl serverless functions invoke shop/hello -p name:Ada
doctl serverless functions get shop/hello --url      # the public URL of a web function
doctl serverless activations logs --last

A web function is then reachable at its URL, for example .../api/v1/web/<namespace>/shop/hello?name=Ada. Everything in args is user input: validate it.

Running it locally with a stand-in invoker

The platform simply imports your module and calls main(args). This stand-in does the same in memory, so you can test your logic before deploying. It is not the real platform: no network, no isolation, no timeout.

Python Stand-in: invoke a Python function locally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Limits, cold starts and billing

  • Time and memory limits. Each function has a maximum run time (you can configure it up to a documented ceiling) and a memory size. Long jobs belong in a worker or job instead.
  • Cold starts. The first request after idle time starts a fresh container, adding latency (often a few hundred milliseconds or more, depending on runtime and size). Later requests reuse the warm container. Keep functions small and avoid heavy imports at module level to reduce it.
  • Stateless. A container may be reused or discarded at any time. Do not keep state in global variables or local files; use a database, Valkey or Spaces.
  • Billing is based on GiB-seconds: memory allocated multiplied by execution time, with a monthly free allowance and a small per-GiB-second price beyond it. Quick, small functions cost almost nothing; verify current allowances on the pricing page.
Python Stand-in: estimate GiB-seconds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Functions inside App Platform

You can also deploy functions as a component of an App Platform app, so one spec manages your static site, API and functions together and routes /api/hello to the function. This is convenient when the functions are part of the same product; standalone namespaces are better for shared utilities used by several apps.

When to use Functions

Good fits: webhooks (payments, Git hosts), contact-form handlers, scheduled tasks, glue code between services, lightweight APIs with bursty traffic.

Poor fits: long-running processes, workloads needing a constant low latency without cold starts, or software that needs system packages or persistent connections. Use App Platform services or Droplets for those.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the entry point of a DigitalOcean Python function by default?

    Functions call main(args), where args is a dictionary of parameters, and use its returned dictionary as the result.
  2. 2. What is a cold start?

    The platform starts a fresh container for the first request after idle time.
  3. 3. Where should a function keep data between invocations?

    Containers are ephemeral and may be replaced at any time, so state must live outside.
  4. 4. How are Functions billed?

    You pay for the resources used while the function runs, after any free allowance.

Summary

  • Functions run small pieces of code on demand in Node.js, Python, Go or PHP, triggered by HTTP, schedules or API calls.
  • A project has packages, functions and a project.yml; the entry point is main(args); deploy with doctl serverless deploy.
  • Functions are stateless, have time and memory limits, suffer occasional cold starts, and are billed in GiB-seconds.
  • Use them for webhooks, glue and scheduled tasks; use services, workers or Droplets for long-running work.

Next: DigitalOcean Kubernetes: Clusters and Node Pools