# Effect.fn: functions with names and traces

- Published: 2026-11-09
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-2-effect-fn-functions-with-names-and-traces/

> Part 2 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-2), 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.[^llms] 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:

```ts title="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)
}
```

```text title="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](/writing/learning-effect-8-services-without-the-ceremony/) uses, and there's nothing wrong with it as code:

```ts title="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`:

```text title="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:

```ts title="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:

```ts title="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:

```text title="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:

**Stack traces for the same failed lookup.** The same lookup of a missing user, written three ways:

- **Plain async Node** (`async function getUser(id) { return await findUser(id) }`). 3 frames: the thrower, its caller, and the top-level call.

```text
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
```
- **Effect.gen wrappers** (`const getUser = (id) => Effect.gen(function* () { … })`). 1 frame: where the error was built. No function names, no callers.

```text
UserNotFound: user 2 not found
    at src/part-2/gen-wrappers.ts:11:30
```
- **Effect.fn** (`const getUser = Effect.fn("getUser")(function* (id) { … })`). 5 frames: every named function twice, once where it was called and once where it was defined.

```text
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:

```text title="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`:

```ts title="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)),
  )
```

```text title="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.[^llms]

**Quiz:** 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?

- GET /users/:id, as a failure
- None. Timeouts aren't recorded on spans
- A separate span named after Effect.timeout

**Answer:** GET /users/:id, as a failure — Extra arguments run inside the span, so the timeout fails the handler's span before it closes. Piped at the call site, it would happen after the span ended.

- Not "None. Timeouts aren't recorded on spans": A timeout is a failure like any other. Whatever span is open when it happens ends as a failure.
- Not "A separate span named after Effect.timeout": Only Effect.fn with a name opens a span here. Effect.timeout doesn't make its own.

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:

```ts title="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*`.

**Quiz:** 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?

- Nothing. It compiles, and the error becomes a success value
- TS2322: UserNotFound is not assignable to User
- TS2488: it must have a [Symbol.iterator]() method

**Answer:** Nothing. It compiles, and the error becomes a success value — UserNotFound has an id and, as an Error, a name. Structurally it's a User, so the annotation can't tell them apart.

- Not "TS2322: UserNotFound is not assignable to User": That's what you get when the success type is something an Error can't fit, like a string.
- Not "TS2488: it must have a [Symbol.iterator]() method": That one is for yield* on something that isn't an Effect, like a function you forgot to call.

## 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`:

```text title="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:[^llms]

- **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.

**Quiz:** isValidSku runs on every line of a 200,000-row import and never fails in an interesting way. How do you write it?

- Effect.fnUntraced
- Effect.fn("isValidSku")
- A function that returns Effect.gen

**Answer:** Effect.fnUntraced — No span and no stack capture. In my one benchmark run it was about 15 times cheaper per call than the named form.

- Not "Effect.fn("isValidSku")": That's 200,000 spans nobody will read.
- Not "A function that returns Effect.gen": Effect's guide says to avoid those. fnUntraced is faster and keeps the same shape.

The code for this part is at the [part-2 tag](https://github.com/devtrillo/effect-on-the-backend/tree/part-2). `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.

[^llms]: [`LLMS.md`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/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`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/src/Effect.ts) describes the extra arguments and the generator reuse. The v4 docs site has no page for `Effect.fn` yet.

- **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.
