pre or post? Picking the right timing for a function
Published 2 min readAlso in Spanish
Groveback functions on database triggers come in two timings, and choosing wrong shows up as
“why is ctx undefined?” or “why is my write so slow?”.
pre: inside the write
A pre hook runs synchronously, inside the write. It can reject the document or rewrite
it before it’s stored:
export default async (event) => {
if (!event.document.email?.includes('@')) {
return { abort: true, reason: 'email is invalid' };
}
return { document: { ...event.document, email: event.document.email.toLowerCase() } };
};
Use it for validation and normalization that must hold for every write. What it does not
get: a ctx at all — so no ctx.db, no integrations. It’s a pure function of the incoming
document, on purpose: a hook that queried the database mid-write would make every write as
slow as its slowest lookup.
It’s also on a tight budget: 2 s per hook (a larger timeoutMs is clamped) and 5 s for
the whole chain of pre hooks on one write.
post: after the write
post is the default. It runs asynchronously, after the write commits, from a queue. This
is where side effects live: send an email, call a webhook, update an aggregate. And this is
where ctx.db is available.
export default async (event, ctx) => {
const total = await ctx.db.count('orders', { ownerId: event.document.ownerId });
await ctx.db.upsertOne('stats', { id: event.document.ownerId }, { $set: { orders: total } });
};
One thing to remember about ctx.db
ctx.db is a service-role handle: it runs below the policy engine. Your end user’s
policies don’t apply inside a function, so the function itself is responsible for only
touching what it should. Functions are sandboxed — the worker has no Mongo client and no
secrets, and every call goes through the host — but the authorization decision is yours.
Rule of thumb
| You want to… | Use |
|---|---|
| Reject or reshape a document before it’s saved | pre |
| Read or write other collections | post |
| Talk to the outside world | post |
More in the functions guide.