Effect.fn: functions with names and traces

By Esteban Trillo7 min readupdated Effect on the BackendEffectTypeScript

Same lookup, same failure. Wrap it in Effect.fn and the callers come back.
Same lookup, same failure. Wrap it in Effect.fn and the callers come back.

Part 2 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the part-2 tag.

I ported a user lookup from plain async Node to Effect, made it fail on purpose, and the stack trace got shorter. Node had told me which function threw and who called it. Effect told me a line number, and nothing about how the program got there.

The fix is one wrapper per function. It has been in Effect since 3.11, and Effect’s own LLMS.md guide for v4 makes it the default for reusable functions.1 This part is what it actually does to a backend, and the two places it bites.

The plain Node version

Here’s the lookup without Effect. findUser throws when the id is missing, and getUser is the handler that calls it:

src/part-2/plain-node.ts
async function findUser(id: string) {
const user = await db.get(id)
if (!user) throw new UserNotFound(id)
return user
}
async function getUser(id: string) {
return await findUser(id)
}
node src/part-2/plain-node.ts
Error: user 2 not found
at findUser (src/part-2/plain-node.ts:19:20)
at async getUser (src/part-2/plain-node.ts:24:10)
at async src/part-2/plain-node.ts:33:5

That’s a good trace. V8’s async stack traces keep the caller as long as you await. Drop the await and write return findUser(id), and the getUser frame disappears. The same file runs both versions so you can see it.

Spans are a different story. In plain Node you get one only if you write it: tracer.startActiveSpan("getUser", …), a try, and a span.end() in the finally, in every function you care about.

The naive port

The obvious Effect version is a function that returns Effect.gen. It’s the shape the fetchUser in Learning Effect part 8 uses, and there’s nothing wrong with it as code:

src/part-2/gen-wrappers.ts
const findUser = (id: string) =>
Effect.gen(function* () {
const user = rows.get(id)
if (!user) return yield* new UserNotFound({ id })
return user
})
const getUser = (id: string) =>
Effect.gen(function* () {
return yield* findUser(id)
})

Run it with Effect.runPromiseExit and print the failure with Cause.pretty:

node src/part-2/gen-wrappers.ts
UserNotFound: user 2 not found
at src/part-2/gen-wrappers.ts:11:30

One frame. It points at the line that built the error. findUser and getUser aren’t in it.

Here’s my reading of why. Calling getUser("2") doesn’t run anything. It builds a description and returns it. By the time the runtime executes that description, I’d expect both functions to have returned already, so no JavaScript call stack is left that remembers who called whom. You get whatever Effect captured when the error was made.

Effect.fn

Effect.fn("name") takes a generator function and gives you back a plain function with the same arguments, which returns an Effect. Here’s Users.find from part 1, rewritten:

src/Users.ts
find: Effect.fn("Users.find", { attributes: { "db.system": "memory" } })(
function* (id: string) {
yield* Effect.annotateCurrentSpan("user.id", id)
const user = rows.get(id)
if (!user) return yield* new UserNotFound({ id })
return user
},
),

And a getUser program on top of it, which part 3 turns into a handler:

src/getUser.ts
export const getUser = Effect.fn("getUser")(function* (
id: string,
): Effect.fn.Return<User, UserNotFound, Users> {
const users = yield* Users
return yield* users.find(id)
})

src/main.ts runs getUser("1") and getUser("2") and prints Cause.pretty for the failure:

npm start
found Ada
UserNotFound: user 2 not found
at Object.<anonymous> (src/Users.ts:23:34)
at Users.find (src/getUser.ts:8:23)
at Users.find (definition) (src/Users.ts:19:18)
at getUser (src/main.ts:7:5)
at getUser (definition) (src/getUser.ts:4:31)

Five frames, and two per function. Each call records a frame with the function’s name and the line it was called from. Its parent frame, (definition), points at where the function was written. So Users.find was called from getUser.ts line 8, and it lives at Users.ts line 19. That’s more than plain Node gave me, and it doesn’t care whether you remembered an await.

It’s still lazy. getUser("2") runs nothing; it returns an Effect, the same as the Effect.gen version did, and running that Effect twice runs the body twice. What changed is that the function now carries a name, and every call leaves a record of where it came from.

Compare the three traces side by side:

How getUser and findUser are written
async function getUser(id) { return await findUser(id) }

3 frames: the thrower, its caller, and the top-level call.

Error: user 2 not found
    at findUser (src/part-2/plain-node.ts:19:20)
    at async getUser (src/part-2/plain-node.ts:24:10)
    at async src/part-2/plain-node.ts:33:5
const getUser = (id) => Effect.gen(function* () { … })

1 frame: where the error was built. No function names, no callers.

UserNotFound: user 2 not found
    at src/part-2/gen-wrappers.ts:11:30
const getUser = Effect.fn("getUser")(function* (id) { … })

5 frames: every named function twice, once where it was called and once where it was defined.

UserNotFound: user 2 not found
    at Object.<anonymous> (src/Users.ts:23:34)
    at Users.find (src/getUser.ts:8:23)
    at Users.find (definition) (src/Users.ts:19:18)
    at getUser (src/main.ts:7:5)
    at getUser (definition) (src/getUser.ts:4:31)

One thing I added along the way: UserNotFound now has a message getter. A Data.TaggedError with no message prints UserNotFound: and nothing after the colon.

Spans you didn’t write

The name you pass is also a span name. Every call to a named Effect.fn opens a tracing span, and nested calls nest. There’s no exporter in the repo until part 15, so src/part-2/spans.ts provides a tracer that keeps spans in an array and prints them:

node src/part-2/spans.ts
--- getUser("1"), then getUser("2")
getUser Success {}
Users.find Success {"db.system":"memory","user.id":"1"}
getUser Failure {}
Users.find Failure {"db.system":"memory","user.id":"2"}

Two kinds of attributes show up there. The ones that never change go in the options object, like "db.system". The ones that depend on the call go through Effect.annotateCurrentSpan, like "user.id".

Only the named form makes a span. Effect.fn(body) with no name records the stack frame and skips the span. Effect.fnUntraced does neither. Name the functions Service.method now. When part 15 ships these spans to a collector, those names are what you’ll search for.

Extra arguments run inside the span

Effect.fn takes more arguments after the generator. Each one works like a step in pipe: it gets the Effect, plus the function’s original arguments. The difference from .pipe is where it runs. The source applies those steps first, and only then wraps the whole thing in the span.

Here’s why that matters. Both of these recover from UserNotFound and return null:

src/part-2/spans.ts
const inside = Effect.fn("inside")(
function* (id: string) {
return yield* getUser(id)
},
Effect.catchTag("UserNotFound", () => Effect.succeed(null)),
)
const outsideBase = Effect.fn("outside")(function* (id: string) {
return yield* getUser(id)
})
const outside = (id: string) =>
outsideBase(id).pipe(
Effect.catchTag("UserNotFound", () => Effect.succeed(null)),
)
node src/part-2/spans.ts
inside: Success
outside: Success
--- catchTag inside vs outside
inside Success {}
getUser Failure {}
Users.find Failure {"db.system":"memory","user.id":"2"}
outside Failure {}
getUser Failure {}
Users.find Failure {"db.system":"memory","user.id":"2"}

Both callers got null. But the outside span says it failed, because the span had already closed when .pipe caught the error. In a trace viewer that request shows up red, even though nothing went wrong for the user. Effect’s own agent guide says it directly: don’t use .pipe with Effect.fn, pass the steps as arguments.1

A handler is Effect.fn("GET /users/:id")(…) and passes Effect.timeout("2 seconds") as an extra argument. A slow lookup times out. Which span records the timeout?

That’s also where timeouts and retries go when part 13 adds them.

What the types tell you

Hover getUser without the annotation, and TypeScript infers (id: string) => Effect<User, UserNotFound, Users>. The success value, the error and the requirement are all in the type. That’s the contract the HTTP handlers in part 3 will lean on.

The Effect.fn.Return<User, UserNotFound, Users> annotation on the generator pins that contract down. You need it for recursive functions, where inference gives up, and it’s worth writing on anything another module calls. It also catches the mistake I make most often, forgetting yield* in front of an error:

src/part-2/mistakes.ts
// Forgot `yield*`: the error is returned as a value, so it lands in the success type.
const findName = Effect.fn("findName")(function* (id: string) {
const user = rows.get(id)
if (!user) return new UserNotFound({ id })
return user.name
})
// Compiles: the error channel is `never`.
export const loose: Effect.Effect<unknown, never> = findName("2")

That compiles. The type is now Effect<string | UserNotFound, never>, so the “error” is a successful result, and nothing downstream will ever catch it. Add Effect.fn.Return<string, UserNotFound> and tsc stops you with TS2322: Type 'UserNotFound' is not assignable to type 'string'.

Don’t lean on that too hard, though. The same mistake in a function that returns a User still compiles with the annotation. An Error has a name, and a UserNotFound has an id, so it fits the shape of User. The file keeps that case too, as a warning. Read every return new …Error as a bug until you see the yield*.

A function annotated with Effect.fn.Return<User, UserNotFound> does `return new UserNotFound({ id })` without yield*. User is { id: string; name: string }. What does tsc say?

When not to bother

Every named call captures two stack locations and opens a span, and that isn’t free. src/part-2/bench.ts calls a trivial function 200,000 times each way, inside one Effect.runSync:

node src/part-2/bench.ts
Effect.gen wrapper 667 ns/call
Effect.fn(name) 2564 ns/call
Effect.fnUntraced 168 ns/call

That’s one run of a microbenchmark on my laptop, with no exporter attached, so read the numbers as orders of magnitude and nothing finer. A few microseconds per request is nothing next to a database round trip. It does add up for a small helper called on every row of a big import.

So the rule I use, and the one in Effect’s guide:1

  • Handlers and service methods: Effect.fn("Service.method"). These are the frames and spans you’ll want at 3am.
  • Helpers on a hot path, and library code: Effect.fnUntraced. It also beats the plain Effect.gen wrapper, which the guide says to avoid. It reuses the generator body instead of building a new closure on every call.
  • One-off effects inside a function: plain Effect.gen. If there’s no function, there’s nothing to name.
isValidSku runs on every line of a 200,000-row import and never fails in an interesting way. How do you write it?

The code for this part is at the part-2 tag. Users.find and getUser are both Effect.fn now, and src/part-2/ has every script above, so you can run them and compare the output with mine.

Next in the series: a Node server in 20 lines, where getUser becomes an HTTP handler.

  • Part 3 — A Node server in 20 lines: getUser becomes GET /users/:id, served by HttpRouter and one NodeRuntime.runMain, with a request log and a clean Ctrl+C for free.

Footnotes

  1. LLMS.md at the effect@4.0.5 tag: “For reusable functions, prefer Effect.fn("name") when tracing is useful and Effect.fnUntraced when it is not, particularly in library implementations and hot paths.” The Effect.fn JSDoc in Effect.ts describes the extra arguments and the generator reuse. The v4 docs site has no page for Effect.fn yet. ↩ ↩2 ↩3

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.