Skip to content

Algebraic data types

Relay lets customers write routing rules: “send GitHub pushes to Slack, unless the event is a ping”. Version one stored a rule as a row with nullable columns, source, header_name, header_value, negate, parent_id, and a kind string. Rows with a header_name but no header_value reached production, and the evaluator treated them as “matches everything”.

An algebraic data type (ADT) is a type built from only two operations, and that is enough to describe data so that the illegal rows cannot be written down. This lesson names the two operations, shows how to count what a type allows, and models the rule tree.

A product type holds several values at once. A record or a tuple is a product: a Job has an id AND a kind AND a payload. A sum type holds exactly one of several alternatives. A union is a sum: a Source is "github" OR "stripe" OR "gitlab".

// Product: both fields are always present.
interface Delivery {
readonly source: "github" | "stripe"
readonly attempt: 1 | 2 | 3
}
// Sum: exactly one variant, tagged so you can tell which.
type Outcome =
| { readonly _tag: "Delivered"; readonly at: number }
| { readonly _tag: "Rejected"; readonly status: number }
| { readonly _tag: "TimedOut" }

Records and tuples are products, discriminated unions are sums. Products let you say “and”, sums say “or”, and between them you can describe most data.

The inhabitants of a type are the values it allows. For finite types you can count them, and the counts follow arithmetic:

  • boolean has 2, "a" | "b" | "c" has 3, undefined has 1, never has 0.
  • A product multiplies: |A × B| = |A| · |B|. Delivery above has 2 · 3 = 6 values.
  • A sum adds: |A + B| = |A| + |B|. boolean | undefined has 3.

Why count? Because the count tells you if the type is the right size for the facts. Relay’s old job status was two flags:

interface JobFlags {
readonly running: boolean
readonly failed: boolean
}
// 2 · 2 = 4 values. Pending, running, failed, and "running and failed at once".

Four states, but only three are real. The fourth is an illegal state that the type permits, so every function that reads the flags must remember to handle it, and some did not. Write the facts as a sum and the count is exactly three. The states from M2 were this idea applied to a state machine:

type JobState =
| { readonly _tag: "Pending" }
| { readonly _tag: "Running"; readonly startedAt: number }
| { readonly _tag: "Failed"; readonly reason: string }

Data now lives only in the variant that has it: a Failed job has a reason, a Pending job cannot have one. “Make illegal states unrepresentable” means choosing the type whose count equals the number of real cases.

A sum can contain itself. A routing rule is either a test on the webhook or a combination of other rules:

type Rule =
| { readonly _tag: "And"; readonly rules: readonly Rule[] }
| { readonly _tag: "Or"; readonly rules: readonly Rule[] }
| { readonly _tag: "Not"; readonly rule: Rule }
| { readonly _tag: "SourceIs"; readonly source: string }
| { readonly _tag: "HeaderEquals"; readonly name: string; readonly value: string }
const rule: Rule = {
_tag: "And",
rules: [
{ _tag: "SourceIs", source: "github" },
{ _tag: "Not", rule: { _tag: "HeaderEquals", name: "x-event", value: "ping" } },
],
}

Every case has exactly the fields it needs. A HeaderEquals always has both a name and a value, so the half-filled row from version one cannot be constructed. And, Or and Not are the branches, SourceIs and HeaderEquals are the leaves. A tree of these is a value you can store as JSON, print, compare and send over the network.

Small constructor functions make the trees readable:

type Rule =
| { readonly _tag: "And"; readonly rules: readonly Rule[] }
| { readonly _tag: "Not"; readonly rule: Rule }
| { readonly _tag: "SourceIs"; readonly source: string }
| { readonly _tag: "HeaderEquals"; readonly name: string; readonly value: string }
const and = (...rules: readonly Rule[]): Rule => ({ _tag: "And", rules })
const not = (rule: Rule): Rule => ({ _tag: "Not", rule })
const sourceIs = (source: string): Rule => ({ _tag: "SourceIs", source })
const headerEquals = (name: string, value: string): Rule => ({ _tag: "HeaderEquals", name, value })
const rule = and(sourceIs("github"), not(headerEquals("x-event", "ping")))
console.log(rule)

You consume a sum with a switch on the tag. One case per variant, and no default, so the compiler checks you covered all of them. Recursive variants recurse:

interface RawWebhook {
readonly source: string
readonly headers: Readonly<Record<string, string>>
readonly body: string
}
type Rule =
| { readonly _tag: "And"; readonly rules: readonly Rule[] }
| { readonly _tag: "Or"; readonly rules: readonly Rule[] }
| { readonly _tag: "Not"; readonly rule: Rule }
| { readonly _tag: "SourceIs"; readonly source: string }
| { readonly _tag: "HeaderEquals"; readonly name: string; readonly value: string }
function evaluate(rule: Rule, webhook: RawWebhook): boolean {
switch (rule._tag) {
case "And":
return rule.rules.every((r) => evaluate(r, webhook))
case "Or":
return rule.rules.some((r) => evaluate(r, webhook))
case "Not":
return !evaluate(rule.rule, webhook)
case "SourceIs":
return webhook.source === rule.source
case "HeaderEquals":
return webhook.headers[rule.name.toLowerCase()] === rule.value
}
}

There is no default and no return after the switch: with all five cases handled the function’s end is unreachable, and TypeScript knows. Add a sixth variant, Xor, and this function stops compiling with “Function lacks ending return statement and return type does not include ‘undefined’” (TS2366), at the exact place that needs a decision. That is the benefit of the sum type that a nullable-column row can never give you.

Model the rule tree and write evaluate(rule, webhook) and describe(rule) with exhaustive switches. The Rule type and its constructors are given. Also finish fromFlags, which maps the old two flags to a JobState, and returns undefined for the one combination that is not a real state. The starter’s functions return fixed values.

  • A product (record, tuple) combines values with “and”, a sum (union) chooses one with “or”.
  • Counts follow arithmetic: products multiply, sums add. Compare the count of a type with the number of real cases.
  • Two booleans make four states. If only three are real, use a sum.
  • A recursive sum models trees such as routing rules, with data only in the variants that need it.
  • Consume a sum with a switch and no default, so adding a variant breaks every function that forgot it.
  • Narrowing: discriminated unions and exhaustiveness checking.