Function best practices

Practical guidelines for writing functions that are fast, secure, observable and easy to change.

Structure

  • One function per responsibility. Group the handlers of one feature (for example "orders") in one function, and put unrelated features in separate functions. Each function has its own workers, dependencies and timeout.
  • Share code through imports. Put helpers in a trigger-less function and import it with @spica-fn/<name> instead of copying code. See Sharing code.
  • Use TypeScript for larger functions, and generate bucket types with spica bucket orm.
  • Keep functions in git with the CLI, and review changes with spica plan before applying them.

Performance

  • Initialize clients at module level. Bucket.initialize, SDK clients and connection pools should be created once per worker, not per event.
  • Return HTTP responses fast. Do slow work after responding, in a bucket trigger, a queue consumer or a schedule.
  • Batch your API calls. Use insertMany, removeMany and the batch endpoint instead of loops of single requests.
  • Ask only for what you need. Send limit, avoid paginate=true unless you need totals, and resolve only the relations you use.
  • Tune per function. Raise concurrencyPerWorker for I/O-bound handlers and add warmWorkers for latency-sensitive endpoints. See Runtime & scaling.

Security

  • Keep credentials in secrets, never in code or environment variables.
  • Give functions narrow API keys. Create an API key per function or feature with only the policies it needs, store it as a secret, and use it with the devkit.
  • Authenticate HTTP routes with authenticate and authorize, and validate request bodies yourself.
  • Remember that API keys bypass rules. When a function acts on behalf of a user, check what that user may do, or forward the user's token to the API instead of using a key.
  • Rate-limit public endpoints with the rateLimit option.

Reliability

  • Make handlers idempotent. Data triggers, schedules and queue consumers can see the same work more than once. Check before you write.
  • Guard against trigger loops. A bucket trigger that writes to its own bucket fires again.
  • Set realistic timeouts and design long jobs as batches that each fit in one event.
  • Acknowledge queue messages explicitly (noAck: false) when losing a message is not acceptable.

Observability

  • Log with levels and include ids so that you can filter and correlate.
  • Watch errors. Filter logs by level 4 in the panel, or send worker output to stdout with --function-worker-log-output and alert on it in your log platform.
  • Name triggers after what they do (onOrderPaid, nightlyReport), because handler names appear in logs.

Local development loop

  1. Start a local instance with spica project start dev.
  2. Fetch your project files with spica fetch.
  3. Run spica dev and edit code. Changes are applied as you save.
  4. Use spica plan to review the changes, commit, and let CI run spica apply against staging and production.