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 planbefore 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,removeManyand the batch endpoint instead of loops of single requests. - Ask only for what you need. Send
limit, avoidpaginate=trueunless you need totals, and resolve only the relations you use. - Tune per function. Raise
concurrencyPerWorkerfor I/O-bound handlers and addwarmWorkersfor 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
authenticateandauthorize, 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
rateLimitoption.
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
4in the panel, or send worker output tostdoutwith--function-worker-log-outputand alert on it in your log platform. - Name triggers after what they do (
onOrderPaid,nightlyReport), because handler names appear in logs.
Local development loop
- Start a local instance with
spica project start dev. - Fetch your project files with
spica fetch. - Run
spica devand edit code. Changes are applied as you save. - Use
spica planto review the changes, commit, and let CI runspica applyagainst staging and production.