Tutorial: Foundational Architecture in Effektive

Topics: Architecture & Design, Languages & Runtimes, Functional & Concurrency

A quote workflow prices items, reserves stock, and saves a quote. Suppose you import a database helper into the workflow to save a line of code. Can the compiler catch that shortcut?

Effektive tracks the database dependency through the helper. It also checks which operations you can retry and generates the Effect 4 code that closes database connections. If the language is new to you, start with the Effektive introduction.

The quote workflow as a design matrix

Nam Suh's Independence Axiom calls for keeping functional requirements independent. The Information Axiom favors designs more likely to meet those requirements. Its measure is I = −log₂ P, where P is the probability of meeting the requirements.

The rows describe what the system must do. The columns name the parts that do the work. An X marks a dependency. A port is a service interface that the host implements.

Requirement          Domain   InventoryPort   QuoteRepoPort + AuditPort
Validate and price     X            0                     0
Reserve inventory      X            X                     0
Save and notify        X            X                     X

The matrix is triangular. Pricing uses the domain types alone. Reserving stock adds the inventory port. Saving the quote and recording the audit add their own ports and depend on successful reservation. The domain checks and resource scopes make the conditions for successful execution explicit.

Before you start

Use Deno 2.9.8 and an Effektive checkout that includes fixtures/axiomatic-hexagonal/. The generated TypeScript targets Effect 4.1.2. The first --tsc build downloads Effect from npm.

Run the commands from the Effektive repository root in the same shell. Create a temporary directory for the example.

quote_dir=$(mktemp -d)
echo "$quote_dir"

To start with the complete example, copy the contents of fixtures/axiomatic-hexagonal/ into $quote_dir and go to step 5. To build it by hand, create these files in $quote_dir.

effektive.json
deno.json
domain.eff
ports.eff
storage.eff
quote.eff
main.ts

Use the default compiler settings in $quote_dir/effektive.json.

{}

Set the Effect version and strict TypeScript options in $quote_dir/deno.json.

{
  "imports": {
    "effect": "npm:effect@4.1.2"
  },
  "compilerOptions": {
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true
  }
}

1. Define the domain types

Put the types and pricing function in $quote_dir/domain.eff. Each where predicate defines which values the type accepts.

export type Int = int
export type Sku = string where s => len(s) > 0
export type Cents = int where c => c >= 0
export type Qty = int where q => q > 0
export type QuoteId = string where id => len(id) > 0

export type LineItem = {
  sku: Sku,
  price: Cents,
  qty: Qty
}

export type Quote = {
  quoteId: QuoteId,
  total: Cents
}

export error OutOfStockError = { sku: Sku }
export error PersistenceError = { reason: string }

const lineTotal = (item: LineItem): Int => Int(item.price) * Int(item.qty)

export const calcSubtotal = (items: LineItem[]): Cents => {
  const sum = items |> fold(0, (acc, item) => acc + lineTotal(item))
  if (sum >= 0) { Cents(sum) } else { Cents(0) }
}

Cents and Qty have distinct type identities even though both use integers. The compiler rejects item.price * item.qty. The two Int(...) calls make the conversion explicit before multiplication.

Cents(sum) needs proof that sum is non-negative. The if gives the compiler that proof, and the other branch returns Cents(0). calcSubtotal generates a synchronous TypeScript function because it performs no effects.

2. Declare the ports and their retry contracts

Declare the service interfaces and their expected failures in $quote_dir/ports.eff. The DbPool service gives the storage adapter its own interface for acquiring a connection.

import { Cents, OutOfStockError, PersistenceError, Qty, QuoteId, Sku } from "./domain.eff"

export service InventoryPort {
  reserve(sku: Sku, qty: Qty): void fails OutOfStockError
}

export service QuoteRepoPort {
  idempotent save(total: Cents): QuoteId fails PersistenceError
}

export service AuditPort {
  logQuote(quoteId: QuoteId): void
}

export type PoolConn = {
  insertQuote: (total: Cents) => QuoteId fails PersistenceError,
  close: () => void
}

export service DbPool {
  acquire(): PoolConn fails PersistenceError
}

QuoteRepoPort.save declares idempotent. The adapter promises that a repeated call has the same effect as a single call. It takes a separate check to establish that a real adapter keeps this promise. InventoryPort.reserve declares neither readonly nor idempotent, so the compiler rejects it inside retry.

3. Close each connection after use

Put the pool adapter in $quote_dir/storage.eff. The using block states how to acquire the connection, use it, and close it.

imports DbPool from "./ports.eff"
import { Cents, QuoteId } from "./domain.eff"

export const saveWithPool = (total: Cents): QuoteId =>
  using (conn = DbPool.acquire()) {
    conn.insertQuote(total)
  } finally {
    conn.close()
  }

imports DbPool lets this module acquire a pool connection. The compiler checks that the connection stays inside using. It generates Effect.acquireUseRelease. After acquisition succeeds, that Effect operation closes the connection on success, expected failure, defect, or interruption.

4. Reserve stock, save the quote, and start the audit

Put the workflow and input decoder in $quote_dir/quote.eff.

imports InventoryPort from "./ports.eff"
imports QuoteRepoPort from "./ports.eff"
imports AuditPort from "./ports.eff"
import { calcSubtotal, LineItem, PersistenceError, Quote } from "./domain.eff"

const itemsSchema: Schema<LineItem[]> = schema()

const persistenceRetry: RetrySchedule<PersistenceError> =
  retrySchedule((_err, attempt) =>
    if (attempt <= 2) { Some(attempt * 5ms) } else { None })

export const createQuote = (items: LineItem[]): Quote => {
  traverse(
    items,
    item => InventoryPort.reserve(item.sku, item.qty),
    { concurrency: "unbounded" },
  )
  const total = calcSubtotal(items)
  const quoteId = retry(
    () => QuoteRepoPort.save(total),
    { schedule: persistenceRetry },
  )
  forkScoped(defer(() => AuditPort.logQuote(quoteId)))
  { quoteId, total }
}

export const submitQuote = (input: unknown): Quote =>
  schemaDecode(itemsSchema, input) |> createQuote

The three imports headers set the limit on service dependencies for this module. The compiler infers the operations and failures for each export. It adds SchemaError to submitQuote because that function decodes untrusted input.

traverse reserves the items concurrently through Effect.forEach. If a reservation fails, Effect interrupts the other reservations still in progress. After the quote is saved, forkScoped starts the audit as a fiber (an Effect task). The audit can have no typed failures, and its lifetime ends with the caller's Scope.

The retry schedule permits two retries of QuoteRepoPort.save after a PersistenceError. The delays are 5ms and 10ms. Effektive generates Effect.retry with a schedule built by Schedule.fromStepWithMetadata.

5. Check what the compiler rejects

First check the complete project.

deno task effektive check "$quote_dir"

The compiler reports 4 modules, 0 diagnostics. Two edits show what happens when the workflow exceeds its declared contracts.

Call the pool adapter from the workflow

In quote.eff, import saveWithPool from ./storage.eff. Replace the retry(...) call with saveWithPool(total). Run the check again.

quote.eff:13:14: error requirement-contract/002: `createQuote` requires undeclared service methods DbPool.acquire
quote.eff:20:19: note: requires `DbPool.acquire` here
quote.eff:25:14: error requirement-contract/002: `submitQuote` requires undeclared service methods DbPool.acquire
quote.eff:26:39: note: requires `DbPool.acquire` here
4 modules, 2 diagnostics

saveWithPool requires DbPool.acquire, so the call brings that requirement into both exports. The compiler reports it because quote.eff lacks an imports DbPool header. Restore quote.eff before the next check.

Retry the inventory reservation

Inside traverse, replace the reservation call with retry(() => InventoryPort.reserve(item.sku, item.qty), { times: 2 }). Run the check again.

quote.eff:15:13: error requirement-contract/003: `retry` cannot replay InventoryPort.reserve, which is not declared `readonly` or `idempotent`
quote.eff:15:25: note: requires `InventoryPort.reserve` here
4 modules, 1 diagnostic

Restore quote.eff before building.

6. Inspect the generated Effect 4 types

Build the project with --tsc to check the generated TypeScript against Effect 4.1.2.

deno task effektive build "$quote_dir" --tsc

Compare the signatures in domain.ts, storage.ts, and quote.ts.

// domain.ts
calcSubtotal: (items: ReadonlyArray<LineItem>) => Cents

// storage.ts
saveWithPool: (total: Cents) => Effect.Effect<QuoteId, PersistenceError, DbPool>

// quote.ts
createQuote: (items: ReadonlyArray<LineItem>) => Effect.Effect<
  Quote,
  OutOfStockError | PersistenceError,
  AuditPort | InventoryPort | QuoteRepoPort | Scope.Scope
>

submitQuote: (input: unknown) => Effect.Effect<
  Quote,
  OutOfStockError | PersistenceError | Schema.SchemaError,
  AuditPort | InventoryPort | QuoteRepoPort | Scope.Scope
>

The compiler generates Schema.TaggedError for each error and Context.Service for each port. The host supplies the services and manages the audit fiber's lifetime through Scope.Scope.

7. Supply the adapters and run the workflow

Put the next two code blocks in $quote_dir/main.ts in order. The first block uses an Effect Layer to supply the pool adapter. The adapter simulates a temporary failure on the first insert so the retry acquires a new connection.

import { Deferred, Effect, Layer } from "effect";
import {
  Cents,
  OutOfStockError,
  PersistenceError,
  Qty,
  QuoteId,
  Sku,
} from "./domain.ts";
import { AuditPort, DbPool, InventoryPort, QuoteRepoPort } from "./ports.ts";
import { createQuote, submitQuote } from "./quote.ts";
import { saveWithPool } from "./storage.ts";

const poolEvents: string[] = [];
const auditLog: string[] = [];
const interrupted: string[] = [];

let dbAttempts = 0;
const DbPoolLive = Layer.succeed(DbPool)({
  acquire: () =>
    Effect.sync(() => {
      dbAttempts += 1;
      const attempt = dbAttempts;
      poolEvents.push(`acquire#${attempt}`);
      return {
        insertQuote: (total) =>
          attempt === 1
            ? Effect.sync(() => {
              poolEvents.push(`fail#${attempt}`);
            }).pipe(
              Effect.andThen(
                Effect.fail(new PersistenceError({ reason: "transient lock" })),
              ),
            )
            : Effect.sync(() => {
              poolEvents.push(`insert#${attempt}:${total}`);
              return QuoteId.make("quote-1");
            }),
        close: () =>
          Effect.sync(() => {
            poolEvents.push(`close#${attempt}`);
          }),
      };
    }),
});

const QuoteRepoFromPool = Layer.succeed(QuoteRepoPort)({
  save: (total) => saveWithPool(total).pipe(Effect.provide(DbPoolLive)),
});

The second block adds inventory and audit adapters. It makes sku-missing fail only after the sku-slow reservation starts. The program uses Effect.scoped to define the lifetime of each workflow run.

const program = Effect.gen(function* () {
  const slowStarted = yield* Deferred.make<void>();
  const auditDone = yield* Deferred.make<void>();

  const InventoryLive = Layer.succeed(InventoryPort)({
    reserve: (sku) => {
      if (sku === "sku-slow") {
        return Deferred.succeed(slowStarted, undefined).pipe(
          Effect.andThen(
            Effect.never.pipe(
              Effect.onInterrupt(() =>
                Effect.sync(() => {
                  interrupted.push(sku);
                })
              ),
            ),
          ),
        );
      }
      if (sku === "sku-missing") {
        return Deferred.await(slowStarted).pipe(
          Effect.andThen(Effect.fail(new OutOfStockError({ sku }))),
        );
      }
      return Effect.void;
    },
  });

  const AuditLive = Layer.succeed(AuditPort)({
    logQuote: (quoteId) =>
      Effect.sync(() => {
        auditLog.push(`audit:${quoteId}`);
      }).pipe(
        Effect.andThen(Deferred.succeed(auditDone, undefined)),
        Effect.asVoid,
      ),
  });

  const LiveLayer = Layer.mergeAll(
    InventoryLive,
    QuoteRepoFromPool,
    AuditLive,
  );

  // 1. Happy path with transient DB failure, retry, pool close, and scoped audit
  const quoted = yield* Effect.scoped(
    Effect.gen(function* () {
      const quote = yield* submitQuote([
        { sku: "sku-a", price: 1000, qty: 2 },
        { sku: "sku-b", price: 500, qty: 1 },
      ]);
      yield* Deferred.await(auditDone);
      return quote;
    }),
  ).pipe(Effect.provide(LiveLayer));

  // 2. Structured concurrency: OutOfStockError cancels sibling fiber immediately
  const outOfStock = yield* Effect.scoped(
    submitQuote([
      { sku: "sku-slow", price: 100, qty: 1 },
      { sku: "sku-missing", price: 200, qty: 1 },
    ]),
  ).pipe(
    Effect.map((quote) => `unexpected:${quote.quoteId}`),
    Effect.catchTag(
      "domain#OutOfStockError",
      (error) => Effect.succeed(`out-of-stock:${error.sku}`),
    ),
    Effect.provide(LiveLayer),
  );

  // 3. Domain design-range enforcement at untrusted boundary
  const invalidInput = yield* Effect.scoped(
    submitQuote([{ sku: "", price: -10, qty: 0 }]),
  ).pipe(
    Effect.map((quote) => `unexpected:${quote.quoteId}`),
    Effect.catchTag(
      "SchemaError",
      (error) => Effect.succeed(`rejected:${error._tag}`),
    ),
    Effect.provide(LiveLayer),
  );

  // 4. Effortless testing: swap QuoteRepoPort with an in-memory double (no DB)
  const InMemoryLayer = Layer.mergeAll(
    InventoryLive,
    Layer.succeed(QuoteRepoPort)({
      save: (_total) => Effect.succeed(QuoteId.make("mem-1")),
    }),
    Layer.succeed(AuditPort)({ logQuote: (_quoteId) => Effect.void }),
  );
  const inMemoryQuote = yield* Effect.scoped(
    createQuote([{
      sku: Sku.make("sku-a"),
      price: Cents.make(750),
      qty: Qty.make(2),
    }]),
  ).pipe(Effect.provide(InMemoryLayer));

  return {
    quoted,
    poolEvents,
    auditLog,
    outOfStock,
    interrupted,
    invalidInput,
    inMemoryQuote,
  };
});

const report = await Effect.runPromise(program);
console.log(JSON.stringify(report));

Type-check and run main.ts.

deno check --config "$quote_dir/deno.json" "$quote_dir/main.ts"
deno run --config "$quote_dir/deno.json" "$quote_dir/main.ts"

The program prints this result.

{"quoted":{"quoteId":"quote-1","total":2500},"poolEvents":["acquire#1","fail#1","close#1","acquire#2","insert#2:2500","close#2"],"auditLog":["audit:quote-1"],"outOfStock":"out-of-stock:sku-missing","interrupted":["sku-slow"],"invalidInput":"rejected:SchemaError","inMemoryQuote":{"quoteId":"mem-1","total":1500}}

The pool events show that the first connection closed before the retry acquired the second. The successful run waits for the audit before the scope closes. When sku-missing fails, Effect interrupts sku-slow. When input decoding fails, the workflow stops before it reaches a port. The final run supplies an in-memory QuoteRepoPort and returns mem-1 without acquiring a connection.

That last run is the useful check when a workflow should stay independent of storage. Supply another implementation of the port and run the same workflow. Then check any promises that belong to the adapter itself, such as what happens when a database write succeeds but the response gets lost.

For a smaller example, see the Effektive library tutorial. The language rules cover service headers, retry annotations, resource scopes, and domain types.