Run Effects at the Edge (Learning Effect, Part 9)

By Esteban Trillo2 min readupdated Learning EffectEffectTypeScript

Build descriptions all the way across. Turn the crank once, at the edge.
Build descriptions all the way across. Turn the crank once, at the edge.

An Effect does not run when you create it.

That was the first weird part.

The next question is where to run it.

My current answer:

Run Effects at the edge.

The plain version

Promises start when you call them.

const getUser = async (id: number) => {
return db.users.findById(id);
};
const pending = getUser(1); // the query is already running

Every async function is its own little edge.

There is no single place where work begins.

That makes it hard to say when something runs.

A promise also cannot be restarted.

To retry, you need the function again, not the promise you already have.

Effect splits that in two.

Building the work is one step. Starting it is another.

The edge is where the outside world calls you

An HTTP handler is an edge.

A CLI command is an edge.

A cron job is an edge.

That is where you turn the Effect description into real work.

export async function GET(request: Request) {
const program = handleRequest(request);
const response = await Effect.runPromise(program);
return response;
}

Which line starts the work?

Helpers should usually return Effects

This is the trap:

const getUser = async (id: number) => Effect.runPromise(fetchUser(id));

That throws away a lot.

Now the caller gets a Promise. The typed error is gone. The requirement handling is hidden. Composition gets worse.

Better:

const getUser = (id: number) => fetchUser(id);

Let the edge run it.

Should a low-level helper usually call runPromise?

Why this feels familiar

This is like keeping business logic out of your route handler.

The route handler receives the world.

The program describes the work.

The runner starts it.

That split keeps the center of the app easier to test and easier to read.

The mistake: runSync on async work

Effect has more than one runner.

Effect.runSync returns the value directly. No await.

It only works when every step is synchronous.

parseUserId from the first part has no async steps, so runSync works there.

const program = Effect.sleep("1 second").pipe(Effect.map(() => "done"));
Effect.runSync(program);

This compiles.

It throws at runtime with an AsyncFiberError.

The type does not track sync versus async. You find out when it runs.

How to spot it: runSync on anything that fetches, sleeps, or talks to a database.

At an edge that can wait, use runPromise.

The fix is small. Swap the runner, add await, and let the edge wait.

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.