zerolith

← All articles

TutorialBillingMCP

Python and Node dependencies: generating an Open Graph image

11 min read

The base image is enough for most handlers. For a compiled package (Pillow in Python, resvg in Node), you build the layer before deploying. Two real examples, og-image and og-image-node, with the price, the limits, an OSV flag in action and the measured cold-start overhead.

Drawing the image that appears when you paste a link into Slack, LinkedIn or Discord takes a drawing library, and none of them is in the base image of a Zerolith function: Pillow in Python, satori and resvg in Node.js. For this case Zerolith has a dedicated step, dependency builds, and this article walks through it on two real functions running in production: og-image (Python), then og-image-node, the same image in Node.js.

You can call the Python version right now: it returns a 1200×630 PNG. Change title, subtitle (up to 70 characters) or add theme=light. The title is capped at 90 characters. The Node version takes the same parameters and returns the same image.

Most handlers need nothing

Before building anything: the Python image already contains flask, requests, httpx, pydantic, python-dateutil, PyYAML and libsql-client (plus certifi and urllib3). The Node image ships axios, lodash, dayjs, uuid, zod, js-yaml, @libsql/client, express, cors, dotenv and @supabase/supabase-js. A dashboard, a webhook, a call to a third-party API: nothing to build, you deploy the file.

A dependency build only makes sense for a package that is not on that list. And it becomes unavoidable when the package is compiled.

Why you cannot just copy the package into your code

A function's code travels as text, and Pillow is a compiled library: its wheel depends on the exact interpreter version. A pip install run on your Mac, or with another Python, would produce files the pod cannot load.

So Zerolith builds the layer itself, as a separate step before the deploy. A Job runs pip install (or npm ci for Node) in your own namespace, the same isolation as your functions, against the exact interpreter of the language you picked: python is CPython 3.12, and there are python313, python314, nodejs22 and nodejs24. When the pod starts, the layer is mounted read-only (for Python, at /deps/python, on the import path).

Python reads requirements.txt, Node reads package-lock.json (with the neighbouring package.json), always at the root of the file tree.

og-image's requirements.txt

requirements.txt
pillow==13.0.0
font-source-sans-pro==0.0.1

Two lines, and the second needs explaining. The first version drew with Pillow's built-in default font. What we observed: "dépendances" came out as "d▯pendances". That font has no accented letters, which rules it out for a title in French or Spanish.

So you need a real font, and a .ttf file cannot ride along with the code, since a function's files only carry text. The answer is a PyPI package that ships the font: font-source-sans-pro brings Source Sans Pro, under the OFL 1.1 licence. It goes through the same build as Pillow.

main.py: loading the fonts
import os

import font_source_sans_pro
from PIL import Image, ImageDraw, ImageFont

def _font(weight, size):
    path = os.path.join(font_source_sans_pro.font_directory, f"SourceSansPro-{weight}.ttf")
    return ImageFont.truetype(path, size)

# Loaded once, when the pod starts, not on every request.
TITLE_FONTS = {size: _font("Bold", size) for size in (80, 68, 56)}
SUBTITLE_FONT = _font("Regular", 38)
BRAND_FONT = _font("Semibold", 30)

The title tries the largest size (80, then 68, then 56 pixels) at which it fits on three lines, and ends with an ellipsis if it still overflows. The handler itself is short:

main.py: the handler
def handler(request):
    q = request.query
    title = _clip(q.get("title", ""), TITLE_MAX) or "Hello from zerolith"
    subtitle = _clip(q.get("subtitle", ""), SUBTITLE_MAX)
    theme = q.get("theme", "dark")
    if theme not in THEMES:
        return 400, {"error": f"theme must be one of {sorted(THEMES)}"}

    started = time.monotonic()
    png = render(title, subtitle, theme)
    return 200, png, {
        "Content-Type": "image/png",
        "Cache-Control": "public, max-age=86400",
        "X-Render-Ms": f"{(time.monotonic() - started) * 1000:.0f}",
        "X-Pillow-Version": PIL_VERSION,
    }

The response body is binary and the Content-Type header does the rest. The one-day Cache-Control keeps a browser from asking for the image on every display. The full code is in the examples repository, folder og-image/.

The three steps

The mechanism is the same for both languages; the example below is the Python one.

1. Start the build. Over MCP with build_dependencies, or through the REST API:

start the build
curl -X POST https://zerolith.io/api/dependencies/builds \
     -H "Authorization: Bearer $JWT" \
     -d '{"language": "python", "files": {"requirements.txt": "pillow==13.0.0\nfont-source-sans-pro==0.0.1\n"}, "force": false}'
# -> 202 {"status": "building", ...}

The answer is a 202 building. If that exact lockfile was already built, you get an immediate 200 ready: nothing is started and nothing is billed. force: true rebuilds the same lockfile, useful when versions are not pinned.

2. Wait for ready. get_dependency_build, or GET /api/dependencies/builds/{id}, until the status is ready. The possible statuses are building, ready, failed (with an error field) and purged. For this lockfile: Job complete in 11 s, build ready 14 s after the request.

3. Deploy with the same files. deploy_function with main.py and the same requirements.txt, handler main.handler. A deploy whose lockfile has no ready build is refused with a 409, with a sentence saying which call to make. We verified it in production: the guard spares you from finding out on the first call that import PIL fails.

Mutations need a verified account. You can also list your builds (list_dependency_builds) or delete one (delete_dependency_build); deletion is refused (409) while the build is running or a function uses it. And as a third option, all of it can be done from the dashboard (Dependencies page).

The same image in Node.js

Same PNG, different language: og-image-node comes down to three packages, none of them in the base Node image.

  • satori 0.63.2 lays out a JSX-like tree (flexbox, text) and produces an SVG. It is pure JavaScript.
  • @resvg/resvg-js 2.6.2 rasterises that SVG into a PNG. It is a native binary (Rust), so the same problem as Pillow: the package has to be the one for the platform. The lockfile lists twelve variants, and npm ci installs only linux-x64-gnu. That is why the build runs in the cluster, with the exact interpreter, and not on your machine.
  • @fontsource/source-sans-3 5.3.1 brings the font, for the same reason as on the Python side. It ships as WOFF, because satori does not read WOFF2.

Node reads package.json and package-lock.json at the root. The lockfile is generated offline, without running a single script:

generate the lockfile
npm install --package-lock-only --ignore-scripts

The build is started like the Python one, with language: "nodejs22" and both files in files. It takes about 31 s and produces a layer of 18.4 MB compressed, 46 MB extracted, 707 files. The native binary loads fine in the nodejs22 image, the layer being resolved through NODE_PATH=/deps/node_modules.

Here is the package.json, with an overrides block we come back to below:

package.json
{
  "dependencies": {
    "@fontsource/source-sans-3": "5.3.1",
    "@resvg/resvg-js": "2.6.2",
    "satori": "0.63.2"
  },
  "overrides": {
    "fflate": "0.7.5"
  }
}

The handler needs no JSX compiler: a satori node is written as the object a compiler would produce, hence the small h() helper. The fonts are read once, when the pod starts:

main.js: fonts and helper
const fs = require('node:fs');
const satori = require('satori').default;
const { Resvg } = require('@resvg/resvg-js');

// Read once, when the pod starts, not on every request.
const font = (weight) =>
  fs.readFileSync(
    require.resolve(`@fontsource/source-sans-3/files/source-sans-3-latin-${weight}-normal.woff`),
  );
const FONTS = [
  { name: 'Source Sans 3', data: font(400), weight: 400, style: 'normal' },
  { name: 'Source Sans 3', data: font(700), weight: 700, style: 'normal' },
];

// A satori node: the object form of JSX, so no compiler is needed.
const h = (type, style, children) => ({ type, props: { style, children } });

Rendering is two lines, SVG then PNG, and the return value is the same triplet as on the Python side:

main.js: render and response
  const started = performance.now();
  const svg = await satori(tree(title, subtitle, THEMES[theme]), { width: W, height: H, fonts: FONTS });
  const png = new Resvg(svg).render().asPng();
  return [200, png, {
    'Content-Type': 'image/png',
    'Cache-Control': 'public, max-age=86400',
    'X-Render-Ms': (performance.now() - started).toFixed(0),
  }];

One pitfall we hit: in satori, a text block must be given an explicit width, otherwise lineClamp constrains nothing and the text runs off the right edge. The full code is in the examples repository, folder og-image-node/.

What it weighs and what it costs

The Python build of og-image produces an artifact of 9.8 MB compressed, 26 MB extracted (275 files); that of og-image-node, 18.4 MB and 46 MB (707 files). The cost has three parts.

  • Build time is billed like compute, at the usual compute prices, and a build that fails is billed too.
  • Storage is free up to 10 MB per account. Beyond that, a paid account pays €0.40 per GB per month. A trial account is not billed: it is capped at 100 MB of storage.
  • The size of one artifact is limited to 50 MiB compressed on trial, 250 MiB on a paid account.

Unused builds are deleted automatically after 30 days (status purged); deploying that lockfile later then requires a new build. On limits: 6 builds per hour per account, one at a time; a refusal (429) says in Retry-After when to try again.

After each build, the installed packages are checked against the OSV database (osv.dev). The vulns field lists {name, version, ids}: [] means no known vulnerability was found, null means the scan has not run yet. It is an indicator, never a gate: a build with known vulnerabilities can still be deployed, and the call is yours. For og-image, vulns is []. The first Node build, however, flagged something.

The indicator in practice: fflate

The first build of og-image-node reported fflate@0.7.3 (GHSA-px8p-9vwx-vf98): an infinite loop in unzipSync() on a crafted ZIP64 archive, fixed in 0.7.5 and 0.8.3. Satori pins fflate to an exact version, so an ordinary update fixes nothing. And the flaw is not reachable here: the function never decompresses user-supplied data, and satori only uses fflate on its own fonts. The build was therefore still deployable, which is exactly the job of an indicator: flag, without blocking.

We fixed it anyway, with the overrides block seen above ("fflate": "0.7.5") and a regenerated lockfile, in which only the fflate entry changes. The PNG produced is byte-for-byte identical, the next build returns vulns: [], and the old build was deleted (purged). Fixing without waiting for upstream, or deciding it is not worth it: either way, the call is yours.

What it does to a cold start

Here are the numbers, with their conditions. They come from measurements over the public internet, from scaled-to-zero to first response, at size small (128 Mi, 0.1 vCPU), each function against a function of the same runtime with no layer, cold at the same moment.

Python. Three measurements, og-image against hello:

cold start, Python, size small
og-image   4.58 s   3.81 s   4.06 s    mean 4.15 s
hello      2.75 s   2.09 s   2.12 s    mean 2.32 s

The layer therefore costs about 1.8 s more. Downloading the layer when the pod starts (fetch-deps) was measured: 26 MB in 0.5 s, between 0.5 and 0.7 s across runs. The rest, about 1.2 s, was not broken down. The likely explanation is the Pillow import, the font loading and the first render on 0.1 vCPU, but that is a hypothesis, not a measurement.

Node.js. Six measurements of og-image-node, against timer (Node 24, no layer):

cold start, Node, size small
og-image-node   6.10 s  3.23 s  4.58 s  2.84 s  4.07 s  4.92 s    median 4.3 s
timer           0.96 s to 2.11 s                                  median 1.4 s

Here the layer costs about 2.9 s more, with a fetch-deps of 1.1 to 2.9 s, median 1.6 s: 46 MB and 707 files to download and extract weigh more than 26 MB and 275 files. That is not the whole overhead, and we did not break down the rest.

These figures are the ones after a platform fix shipped the same day. Before it, the Node fetcher went through fetch (undici) and decompressed in 16 KiB blocks, zlib's default: fetch-deps had a median of 2.3 s (2.2 to 3.2 s) and the cold start of og-image-node a median of 5.4 s. The fetcher now uses http.get and decompresses in 1 MiB blocks. We also tried shipping GNU tar in the image: no gain inside the container, since node, tar and gzip share the same CPU quota, and two safety checks would have been lost. We dropped it.

Python (og-image) Node (og-image-node)
Build Job 11 s, ready at 14 s about 31 s
Layer 9.8 MB compressed, 26 MB, 275 files 18.4 MB compressed, 46 MB, 707 files
fetch-deps 0.5 to 0.7 s 1.1 to 2.9 s, median 1.6 s
Cold start mean 4.15 s (3 runs) median 4.3 s (6 runs)
No layer, same moment hello, mean 2.32 s timer, median 1.4 s
Layer overhead about 1.8 s about 2.9 s
Warm 0.14 to 0.16 s 0.12 to 0.18 s

Read this table as orders of magnitude: the nodes are shared, the measurements noisy, a mean of three and a median of six cannot be compared to the decimal, and the two functions do not have the same baseline. What it mostly shows is that the size of the layer is paid on the first call.

Warm, a call takes 0.12 to 0.18 s over the public internet. Whether 4 s on the first call of an idle function is acceptable is for you to judge. If it is not, the levers are:

  • fewer dependencies, or lighter ones: a heavier layer lengthens the start;
  • a larger size, since a small CPU lengthens it too;
  • minScale, which keeps a pod warm and removes the cold start, but is billed like the rest of compute. See hiding the cold start for other options.

Putting the image in a page

Once the function is deployed, the image is referenced like any URL:

html
<meta property="og:image"
      content="https://<function-url>/?title=My+article&subtitle=blog.example.com">

Each page passes its own title in the URL. Social networks call the function when someone shares the link and cache the result, so there is no image to make by hand for each article. A function's access modes (API key, signed URL, public) are described in the article on the HTML dashboard.

The full handler contract is in the documentation, prices on the pricing page, and the MCP server exposes builds as tools, so an agent can write the requirements.txt, start the build and deploy in the same conversation.

Try it on your own account

Signing up comes with credit, enough to deploy, schedule and measure everything above, without getting a card out.

Start for free »