Lab 06: Effect System

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

Effect-TS: typed errors as values, Effect.gen coroutine style, Layer for DI, Scope for resource management, Effect.all for parallel/sequential execution, structured concurrency, and retry policies.


Step 1: Effect Fundamentals

import { Effect, pipe } from 'effect';

// Effect<A, E, R>
//   A = success value type
//   E = error type (typed!)
//   R = requirements/dependencies

// Succeed: wraps a value
const succeed = Effect.succeed(42);                 // Effect<number, never, never>

// Fail: typed error
const fail = Effect.fail(new Error('oops'));        // Effect<never, Error, never>

// Sync: lift synchronous computation
const sync = Effect.sync(() => Math.random());      // Effect<number, never, never>

// Async: wrap a Promise (errors become defects unless handled)
const promise = Effect.promise(() => fetch('/api')); // Effect<Response, never, never>

// Try: Promise that can fail with typed error
const tryPromise = Effect.tryPromise({
  try: () => fetch('/api/users').then(r => r.json()),
  catch: (error) => new NetworkError(String(error)),
}); // Effect<unknown, NetworkError, never>

Step 2: Effect.gen — Coroutine Style


Step 3: Typed Errors as Values


Step 4: Layer — Dependency Injection


Step 5: Scope — Resource Management


Step 6: Effect.all — Parallel Execution


Step 7: Retry Policy


Step 8: Capstone — Effect.gen Pipeline

📸 Verified Output:


Summary

Feature
API
Benefit

Typed errors

Effect<A,E,R>

Compile-time error tracking

Coroutine style

Effect.gen

Readable async code

DI

Layer + Context

Testable, composable

Resources

Scope + acquireRelease

Leak-free cleanup

Parallelism

Effect.all({concurrency})

Controlled parallelism

Retry

Schedule

Exponential backoff

Structured concurrency

Fiber

Cancellable tasks

Last updated