Keel by ChimpLabs
Jump to page or section Esc
Primitives

ExternalSystem

Typed third-party API wrappers with declared secrets, timeouts, retries, and zero-infra mocks.

ExternalSystem wraps third-party APIs you do not own, such as Stripe, Resend, OpenAI, Twilio, Slack, or shipping carriers. Every call validates input and output schemas and applies configured timeouts and retries. Each declaration lists required Secrets so Keel verifies them at boot and provisions them on deploy.

Use ExternalSystem for external vendors. For internal services you own with closed error contracts and monolith-to-microservice extraction, see Service.


Declaring an ExternalSystem

Plain TypeScript SDK (@chimp-labs/keel/sdk)

import { Schema } from "effect"
import { k } from "@chimp-labs/keel/sdk"

export class CardDeclinedError extends Schema.TaggedError<CardDeclinedError>()(
  "CardDeclinedError",
  { code: Schema.String }
) {}

export const StripeKey = k.secret("STRIPE_API_KEY")

export const StripeSystem = k.external("stripe", {
  secrets: [StripeKey],
  timeout: "5 seconds",
  retries: 2,
  operations: {
    charge: {
      input: k.object({ orderId: k.string(), amountCents: k.int() }),
      output: k.object({ chargeId: k.string(), receiptUrl: k.string() }),
      errors: [CardDeclinedError],
    },
    refund: {
      input: k.object({ chargeId: k.string() }),
      output: k.object({ refundId: k.string() }),
    },
  },
})

Configuration options

Option Type Required Description
operations Record<string, { input, output, errors? }> Yes Map of typed vendor operations, their input and output schemas, and optional declared domain error schemas.
secrets readonly SecretDef[] No Required secrets collected by inferKeelInfra and verifySecrets.
timeout Duration.Input No Per-attempt timeout (ExternalSystemTimeoutError on expiry).
retries number No Number of retries for transient infrastructure errors (ExternalSystemCallError and ExternalSystemTimeoutError). Declared domain errors are not retried.

Effect v4 (@chimp-labs/keel/external-system)

import { Schema } from "effect"
import { ExternalSystem } from "@chimp-labs/keel/external-system"

export class CardDeclinedError extends Schema.TaggedError<CardDeclinedError>()(
  "CardDeclinedError",
  { code: Schema.String }
) {}

export class PaymentsSystem extends ExternalSystem<PaymentsSystem>()("payments", {
  secrets: [StripeKey],
  timeout: "5 seconds",
  retries: 2,
  operations: {
    charge: {
      input: Schema.Struct({ orderId: Schema.String, amountCents: Schema.Int }),
      output: Schema.Struct({ chargeId: Schema.String }),
      errors: [CardDeclinedError],
    },
  },
}) {}

Attaching to a service

Listing an ExternalSystem in a service’s dependencies or resources includes its declared secrets in that service unit’s deployment scope and boot preflight:

export const BillingService = k.service("billing", {
  resources: [InvoicesTable],
  dependencies: [StripeSystem],
  operations: { /* ... */ },
})

Operations reference

Binding live implementations and mocks

// Production binding (applies timeout, retries, and schema checks)
await using stripe = await keel.stripe.bind({
  charge: async ({ orderId, amountCents }) => {
    return keel.stripeKey.use(async (apiKey) => {
      const res = await fetch("https://api.stripe.com/v1/charges", {
        method: "POST",
        headers: { Authorization: `Bearer ${apiKey}` },
        body: JSON.stringify({ orderId, amountCents }),
      })
      if (!res.ok) throw new Error(`Stripe HTTP ${res.status}`)
      return res.json()
    })
  },
  refund: async ({ chargeId }) => ({ refundId: `re_${chargeId}` }),
})

const receipt = await stripe.charge({ orderId: "ord_1", amountCents: 4500 })

// Test binding (schema-validated mock with zero network calls)
await using mockStripe = await keel.stripe.bind(
  {
    charge: async () => ({ chargeId: "ch_test", receiptUrl: "https://example.test/r" }),
    refund: async () => ({ refundId: "re_test" }),
  },
  { mock: true }
)

SDK and Effect API mapping

SDK method (keel.<ext>.*) Effect function (@chimp-labs/keel/external-system) Description
bind(handlers) System.layer(handlers) Provides a live client with timeout, retry, and schema guards.
bind(handlers, { mock: true }) System.mock(handlers) Provides a zero-infra test mock with schema validation.
client.<op>(input) yield* System, then sys.<op>(input) Calls an operation through the schema and timeout/retry pipeline.

Errors and failure modes

Operations may declare expected vendor domain errors with errors: [...]. ExternalSystem validates matching errors against their schemas at runtime and passes them through unwrapped on the typed error channel. Declared domain errors do not trigger retries. Any undeclared or malformed error from the vendor adapter is wrapped in ExternalSystemCallError.

Error tag Category HTTP status Retryable When it occurs
Declared errors Domain Custom No Expected vendor business failure listed in operation.errors.
ExternalSystemCallError unavailable 502 Yes Upstream handler threw or returned an undeclared error.
ExternalSystemTimeoutError timeout 504 Yes Call exceeded configured timeout.
SchemaError invalid 400 No Input or vendor response failed schema validation.

Backends and infrastructure

  • ExternalSystem is runtime-agnostic and runs in Memory tests, Node.js, Docker containers, and Cloudflare Workers.
  • inferKeelInfra inspects system.secrets and adds them to the owning service unit’s required secrets and verifySecrets boot checks.
  • Every call records KeelMetrics operation counters and keel.external-system.<op> tracing spans.

Testing in memory

await using keel = await createKeel({
  backend: "memory",
  resources: { stripe: StripeSystem },
})

let attempts = 0
await using stripe = await keel.stripe.bind({
  charge: async () => {
    attempts++
    if (attempts === 1) throw new Error("transient 502")
    return { chargeId: "ch_1", receiptUrl: "https://stripe.test/1" }
  },
  refund: async () => ({ refundId: "re_1" }),
})

const out = await stripe.charge({ orderId: "ord_1", amountCents: 1200 })
// attempts === 2 (automatically retried!), out.chargeId === "ch_1"