---
title: Postgres API
description: Generated public TypeScript reference for @relkit/postgres.
search:
  exclude: true
sidebar:
  icon: braces
---

{/* Generated by apps/docs/scripts/generate.ts. Do not edit. */}

For configuration and examples, read [postgres](/docs/modules/jobs/providers/postgres), [railway](/docs/modules/deployment/railway), [vercel](/docs/modules/deployment/vercel).

## Public imports

- `@relkit/postgres` — 10 exports
- `@relkit/postgres/runtime` — 18 exports
- `@relkit/postgres/drizzle` — 4 exports

## All exported APIs

Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API's inline sample, a maintained repository usage, or the shared module walkthrough.

| API                                                                                                    | Kind  | Import from                | Example                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------ | ----- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| [BackgroundFiber](/docs/api/integrations/postgres#backgroundfiber-type-alias)                          | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [ClaimedOccurrence](/docs/api/integrations/postgres#claimedoccurrence-interface)                       | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [createPostgresEventProvider](/docs/api/integrations/postgres#createpostgreseventprovider)             | Value | `@relkit/postgres/runtime` | [API example](/docs/api/integrations/postgres#createpostgreseventprovider)                                                                 |
| [createPostgresJobsRuntime](/docs/api/integrations/postgres#createpostgresjobsruntime-1)               | Value | `@relkit/postgres/runtime` | [API example](/docs/api/integrations/postgres#createpostgresjobsruntime-1)                                                                 |
| [outbox](/docs/api/integrations/postgres#outbox)                                                       | Value | `@relkit/postgres/drizzle` | [API example](/docs/api/integrations/postgres#outbox)                                                                                      |
| [OutboxOptions](/docs/api/integrations/postgres#outboxoptions-interface)                               | Type  | `@relkit/postgres/drizzle` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [OutboxTransaction](/docs/api/integrations/postgres#outboxtransaction-interface)                       | Type  | `@relkit/postgres/drizzle` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresConnectionOptions](/docs/api/integrations/postgres#postgresconnectionoptions-interface)       | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresDatabase](/docs/api/integrations/postgres#postgresdatabase-interface)                         | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresDatabaseOptions](/docs/api/integrations/postgres#postgresdatabaseoptions-interface)           | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [postgresEvent](/docs/api/integrations/postgres#postgresevent-1)                                       | Value | `@relkit/postgres`         | [API example](/docs/api/integrations/postgres#postgresevent-1)                                                                             |
| [PostgresEventAdapter](/docs/api/integrations/postgres#postgreseventadapter-type-alias)                | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresEventOptions](/docs/api/integrations/postgres#postgreseventoptions-interface)                 | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresEventProvider](/docs/api/integrations/postgres#postgreseventprovider-interface)               | Type  | `@relkit/postgres/runtime` | [Source example](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/tests/conformance/postgres-conformance.ts#L52) |
| [PostgresEventProviderOptions](/docs/api/integrations/postgres#postgreseventprovideroptions-interface) | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresEventTrigger](/docs/api/integrations/postgres#postgreseventtrigger-interface)                 | Type  | `@relkit/postgres/runtime` | [Source example](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/tests/events.test.ts#L54)                      |
| [PostgresFaults](/docs/api/integrations/postgres#postgresfaults-interface)                             | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [postgresJob](/docs/api/integrations/postgres#postgresjob-1)                                           | Value | `@relkit/postgres`         | [API example](/docs/api/integrations/postgres#postgresjob-1)                                                                               |
| [PostgresJobAdapter](/docs/api/integrations/postgres#postgresjobadapter-type-alias)                    | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresJobOptions](/docs/api/integrations/postgres#postgresjoboptions-interface)                     | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresJobsRuntime](/docs/api/integrations/postgres#postgresjobsruntime-interface)                   | Type  | `@relkit/postgres/runtime` | [Source example](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/tests/conformance/postgres-conformance.ts#L96) |
| [PostgresJobsRuntimeOptions](/docs/api/integrations/postgres#postgresjobsruntimeoptions-interface)     | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresJobWorker](/docs/api/integrations/postgres#postgresjobworker-interface)                       | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresOutbox](/docs/api/integrations/postgres#postgresoutbox-interface)                             | Type  | `@relkit/postgres/drizzle` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresTableOptions](/docs/api/integrations/postgres#postgrestableoptions-interface)                 | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresTables](/docs/api/integrations/postgres#postgrestables-interface)                             | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresTaskDefinition](/docs/api/integrations/postgres#postgrestaskdefinition-interface)             | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresUrlInput](/docs/api/integrations/postgres#postgresurlinput-type-alias)                        | Type  | `@relkit/postgres`         | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresWorkerHandle](/docs/api/integrations/postgres#postgresworkerhandle-interface)                 | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresWorkerLoopOptions](/docs/api/integrations/postgres#postgresworkerloopoptions-interface)       | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [PostgresWorkerRegistration](/docs/api/integrations/postgres#postgresworkerregistration-interface)     | Type  | `@relkit/postgres/runtime` | [Module example](/docs/modules/jobs/providers/postgres)                                                                                    |
| [runtimeIntegration](/docs/api/integrations/postgres#runtimeintegration-1)                             | Value | `@relkit/postgres/runtime` | [Source example](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/tests/fixtures/worker-role.ts#L22)             |

## `index.ts`

### "./outbox.js" (namespace export)

Re-exports all named exports from the "./outbox.js" module.

**Signature**

```ts
export * from "./outbox.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/index.ts#L1)

## `outbox.ts`

Transactional outbox for Drizzle. `outbox(tx).publish(event, payload)`
validates the payload against the event contract and writes the envelope
and its per-consumer deliveries with one statement on the caller's Drizzle
transaction, so the event commits or rolls back with the transaction's other
writes. Consumers run later from the Postgres event provider's loops.

### "./outbox.types.js" (namespace export)

Re-exports all named exports from the "./outbox.types.js" module.

**Signature**

```ts
export * from "./outbox.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/outbox.ts#L13)

### outbox

Binds the outbox to a Drizzle transaction (or database) on the backend's Postgres database.

**Example**

```ts
await db.transaction(async (tx) => outbox(tx).publish(orderPlaced, { orderId }));
```

**Signature**

```ts
declare const outbox: <Result>(
  transaction: OutboxTransaction<Result>,
  options?: OutboxOptions,
) => PostgresOutbox;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/outbox.ts#L23)

## `outbox.types.ts`

Contracts of the Drizzle transactional outbox.

### OutboxOptions (interface)

Outbox settings; they must match the event provider's profile and tables.

**Signature**

```ts
export interface OutboxOptions extends PostgresTableOptions {
  /** Event profile used when the event contract names none; defaults to `default`. */
  readonly profile?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/outbox.types.ts#L12)

### OutboxTransaction (interface)

Anything with Drizzle's `execute(sql)`: a Postgres database or transaction.

**Signature**

```ts
export interface OutboxTransaction<Result> {
  readonly execute: (query: SQL) => PromiseLike<Result>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/outbox.types.ts#L7)

### PostgresOutbox (interface)

The outbox bound to one transaction.

**Signature**

```ts
export interface PostgresOutbox {
  /**
   * Writes one event on the bound transaction.
   * @param event - Event contract; the payload is validated against its schema.
   * @param payload - Event payload.
   * @param options - Optional ordering key and attributes.
   * @returns The persisted envelope; consumers see it only if the transaction commits.
   */
  readonly publish: <Id extends string, Version extends number, Input>(
    event: EventDescriptor<Id, Version, Input>,
    payload: Input,
    options?: EventPublishOptions,
  ) => Promise<UnknownEventEnvelope & { readonly eventId: Id; readonly version: Version }>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/drizzle/outbox.types.ts#L18)

## `events-envelope.ts`

Builds the event envelope that publication persists in the outbox. Both the
provider's `publish` and the Drizzle outbox use it, so an event written
inside an application transaction is indistinguishable from one published
directly. Pure construction; no connection is opened.

### createEventEnvelope

Creates a new envelope for one publication.

**Example**

```ts
createEventEnvelope("orders.placed", 1, { orderId: "o-1" }).instanceId.startsWith("event-");
```

**Signature**

```ts
declare const createEventEnvelope: (
  eventId: string,
  version: number,
  payload: UnknownEventEnvelope["payload"],
  options?: EventPublishOptions,
  propagation?: TracePropagation,
) => UnknownEventEnvelope;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/events-envelope.ts#L20)

## `index.ts`

### "./providers.types.js" (namespace export)

Re-exports all named exports from the "./providers.types.js" module.

**Signature**

```ts
export * from "./providers.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/index.ts#L3)

### PostgresEventAdapter

Events provider adapter selected with `postgresEvent()`.

**Signature**

```ts
type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L47)

### PostgresJobAdapter

Jobs provider adapter selected with `postgresJob()`.

**Signature**

```ts
type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L45)

### PostgresTableOptions

Where the backend's tables live; both names are validated SQL identifiers.

**Signature**

```ts
export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L4)

### PostgresTables

Fully qualified, quoted table names for one backend namespace.

**Signature**

```ts
export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L12)

### postgresEvent

**Signature**

```ts
declare const postgresEvent: (options?: PostgresEventOptions) => PostgresEventAdapter;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/index.ts#L1)

### postgresJob

**Signature**

```ts
declare const postgresJob: (options?: PostgresJobOptions) => PostgresJobAdapter;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/index.ts#L1)

## `providers.ts`

Authoring entry for the Postgres backend. `postgresJob()` and `postgresEvent()`
build the provider adapters an application selects in `defineApp({ jobs, events })`.
They validate options and serialize connection and behavior data only; the
runtime entry opens connections when the application starts.

### "./providers.types.js" (namespace export)

Re-exports all named exports from the "./providers.types.js" module.

**Signature**

```ts
export * from "./providers.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L25)

### PostgresEventAdapter (type alias)

Events provider adapter selected with `postgresEvent()`.

**Signature**

```ts
type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L47)

### PostgresJobAdapter (type alias)

Jobs provider adapter selected with `postgresJob()`.

**Signature**

```ts
type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L45)

### postgresConnectionContract

Connection fields both adapters accept.

**Signature**

```ts
declare const postgresConnectionContract: ProviderConnectionContract;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L51)

### postgresEvent

Selects durable Postgres events with per-consumer delivery for an events profile.

**Throws**

TypeError for unknown options or an invalid URL, identifier or duration.

**Example**

```ts
const events = postgresEvent({ url: env.secret("DATABASE_URL") });
```

**Signature**

```ts
declare const postgresEvent: (options?: PostgresEventOptions) => PostgresEventAdapter;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L83)

### postgresIntegration

Integration reference shared by both adapters.

**Signature**

```ts
declare const postgresIntegration: IntegrationReference<"postgres">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L49)

### postgresJob

Selects durable Postgres jobs and schedules for a jobs profile.

**Throws**

TypeError for unknown options or an invalid URL, identifier or duration.

**Example**

```ts
const jobs = postgresJob({ url: env.secret("DATABASE_URL") });
```

**Signature**

```ts
declare const postgresJob: (options?: PostgresJobOptions) => PostgresJobAdapter;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.ts#L60)

## `providers.types.ts`

Authoring contracts for the Postgres jobs and events providers selected in `defineApp`.

### PostgresConnectionOptions (interface)

Connection and table settings shared by the jobs and events providers.

**Signature**

```ts
export interface PostgresConnectionOptions extends PostgresTableOptions {
  /** Postgres connection string; at runtime `RELKIT_POSTGRES_URL` overrides it. */
  readonly url?: PostgresUrlInput;
  /** How long a worker owns a leased run or delivery before another may take it, in ms. */
  readonly leaseMs?: number;
  /** How often idle workers look for due work, in ms. */
  readonly pollIntervalMs?: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.types.ts#L13)

### PostgresEventOptions (interface)

Options for `postgresEvent()`.

**Signature**

```ts
export interface PostgresEventOptions extends PostgresConnectionOptions {}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.types.ts#L26)

### PostgresJobOptions (interface)

Options for `postgresJob()`: connection settings plus the common jobs service options.

**Signature**

```ts
export interface PostgresJobOptions extends PostgresConnectionOptions, JobsServiceOptions {}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.types.ts#L23)

### PostgresUrlInput (type alias)

A connection string given inline or as an environment binding.

**Signature**

```ts
type PostgresUrlInput =
  | string
  | BindingValueRef<string, string, "string">
  | BindingValueRef<string, string, "secret-string">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/providers.types.ts#L7)

## `database.ts`

Owns one Postgres connection pool for a backend namespace. The pool is a
`@effect/sql-pg` Layer held by a ManagedRuntime; acquiring it applies the
idempotent DDL inside a transaction holding an advisory lock, so instances
that start together create the tables once. Background loops are forked into
the same runtime and interrupted before the pool closes.

### "./database.types.js" (namespace export)

Re-exports all named exports from the "./database.types.js" module.

**Signature**

```ts
export * from "./database.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.ts#L20)

### PostgresBackendError (class)

A SQL statement of the Postgres backend failed.

**Signature**

```ts
declare class PostgresBackendError
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.ts#L23)

### backendOperation

Tags SQL failures of one backend operation.

**Signature**

```ts
declare const backendOperation: (
  operation: string,
) => <A, E, R>(
  effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, Exclude<E, SqlError> | PostgresBackendError, R>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.ts#L37)

### openPostgresDatabase

Opens the pool lazily; the first `run` acquires it and creates the schema.

**Example**

```ts
const database = openPostgresDatabase({ url: process.env.DATABASE_URL! });
```

**Signature**

```ts
declare const openPostgresDatabase: (options: PostgresDatabaseOptions) => PostgresDatabase;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.ts#L79)

## `database.types.ts`

Contracts for the shared Postgres connection owner used by the jobs and events runtimes.

### BackgroundFiber (type alias)

A background loop; it can only fail when the pool or schema cannot be acquired.

**Signature**

```ts
type BackgroundFiber = Fiber.Fiber<void, SqlError>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.types.ts#L8)

### PostgresDatabase (interface)

A pooled connection plus the background fibers that depend on it.

**Signature**

```ts
export interface PostgresDatabase {
  /** Quoted table names for this namespace. */
  readonly tables: PostgresTables;
  /**
   * Runs one SQL workflow; the schema is created before the first one runs.
   * @param effect - Workflow requiring the SQL client.
   * @param signal - Optional caller cancellation.
   * @returns The workflow result; failures reject the Promise.
   */
  readonly run: <A, E>(effect: Effect.Effect<A, E, SqlClient>, signal?: AbortSignal) => Promise<A>;
  /**
   * Starts a background workflow that `close()` interrupts before releasing the pool.
   * @param effect - Never-failing loop requiring the SQL client.
   * @returns The running fiber.
   */
  readonly fork: (effect: Effect.Effect<void, never, SqlClient>) => BackgroundFiber;
  /** Interrupts background fibers, then closes the pool. Safe to call twice. */
  readonly close: () => Promise<void>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.types.ts#L19)

### PostgresDatabaseOptions (interface)

Connection settings for one backend namespace.

**Signature**

```ts
export interface PostgresDatabaseOptions extends PostgresTableOptions {
  /** Postgres connection string. */
  readonly url: string;
  /** Pool size; defaults to 10. */
  readonly maxConnections?: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/database.types.ts#L11)

## `events-provider.ts`

The Postgres event provider. Registering a durable trigger records its
consumer row; `publish` persists the envelope and one delivery per consumer
in a single statement; consumer loops lease due deliveries with
`FOR UPDATE SKIP LOCKED`, invoke the trigger, and complete, retry or
dead-letter each delivery on its own under the trigger's retry policy.
Delivery is at least once: a consumer that crashes after its handler
succeeded is invoked again when its lease expires.

### "./events-provider.types.js" (namespace export)

Re-exports all named exports from the "./events-provider.types.js" module.

**Signature**

```ts
export * from "./events-provider.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-provider.ts#L24)

### createPostgresEventProvider

Creates the Postgres event provider for one profile.

**Throws**

TypeError when neither `url` nor `database` is given.

**Example**

```ts
const events = createPostgresEventProvider({ url: process.env.DATABASE_URL! });
```

**Signature**

```ts
declare const createPostgresEventProvider: (
  options: PostgresEventProviderOptions,
) => PostgresEventProvider;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-provider.ts#L41)

## `events-provider.types.ts`

Contracts of the Postgres event provider: options, trigger bindings and the provider surface.

### PostgresEventProvider (interface)

The Postgres event provider.

**Signature**

```ts
export interface PostgresEventProvider extends EventProvider {
  readonly database: PostgresDatabase;
  readonly registerContract: (contract: object) => Promise<void>;
  readonly registerTrigger: (binding: PostgresEventTrigger) => Promise<void>;
  /** Runs at most one due delivery per durable consumer; resolves the number delivered. */
  readonly deliverDue: () => Promise<number>;
  /** Starts the consumer loop; idempotent. */
  readonly startConsumers: () => void;
  readonly close: () => Promise<void>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-provider.types.ts#L39)

### PostgresEventProviderOptions (interface)

Options for `createPostgresEventProvider`.

**Signature**

```ts
export interface PostgresEventProviderOptions extends Partial<PostgresDatabaseOptions> {
  /** Shared connection owner; when given, `url` is ignored and `close()` leaves it open. */
  readonly database?: PostgresDatabase;
  /** Event provider profile; consumers and deliveries are namespaced by it. Defaults to `default`. */
  readonly profile?: string;
  /** Delivery lease duration in ms; defaults to 30 000. */
  readonly leaseMs?: number;
  /** Idle polling interval of consumer loops in ms; defaults to 1 000. */
  readonly pollIntervalMs?: number;
  /** Run consumer loops in this instance; false for `api`-role instances. Defaults to true. */
  readonly consumers?: boolean;
  /** Prefix of delivery owner tokens. */
  readonly workerId?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-provider.types.ts#L23)

### PostgresEventTrigger (interface)

The trigger binding the runtime registers for each event-only function.

**Signature**

```ts
export interface PostgresEventTrigger {
  readonly id: string;
  readonly eventId: string;
  readonly eventVersion: number;
  /** `durable` triggers get persisted deliveries; `ephemeral` ones run in-process after publish. */
  readonly delivery: "durable" | "ephemeral";
  /** Retry policy: `maxAttempts`, `initialDelayMs`, `maxDelayMs`, `multiplier`, `jitter`. */
  readonly retry?: JsonValue;
  readonly timeoutMs?: number;
  readonly invoke: (
    envelope: UnknownEventEnvelope,
    options?: { readonly replayed?: boolean; readonly deadlineMs?: number },
  ) => Promise<JsonValue | void | object>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-provider.types.ts#L7)

## `events-store.ts`

SQL for durable events. Publication is one statement: it inserts the
envelope into the outbox and, from the registered consumers of that event
version, one delivery row per consumer, so the event and its deliveries
commit or roll back together. Each delivery is leased, retried and
dead-lettered on its own, so one failing consumer never re-runs another.

### DeliveryRow

A leased delivery joined with its outbox envelope.

**Signature**

```ts
export interface DeliveryRow {
  readonly instance_id: string;
  readonly trigger_id: string;
  /** One-based attempt this lease runs. */
  readonly attempt: number;
  readonly envelope: UnknownEventEnvelope;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.types.ts#L5)

### leaseDelivery

Leases the oldest due delivery of one consumer, including ones whose lease expired.

**Signature**

```ts
declare const leaseDelivery: (
  tables: PostgresTables,
  profile: string,
  triggerId: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<DeliveryRow | undefined, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.ts#L71)

### publishEvent

Persists an envelope and fans it out to the event's registered consumers.

**Signature**

```ts
declare const publishEvent: (
  tables: PostgresTables,
  profile: string,
  envelope: UnknownEventEnvelope,
) => Effect.Effect<number, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.ts#L24)

### registerConsumer

Records a durable consumer so later publications create deliveries for it.

**Signature**

```ts
declare const registerConsumer: (
  tables: PostgresTables,
  profile: string,
  consumer: { readonly triggerId: string; readonly eventId: string; readonly version: number },
) => Effect.Effect<void, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.ts#L50)

### settleDelivery

Settles a leased delivery, fenced on its owner token.

**Signature**

```ts
declare const settleDelivery: (
  tables: PostgresTables,
  delivery: Pick<DeliveryRow, "instance_id" | "trigger_id">,
  owner: string,
  outcome:
    | { readonly state: "completed" }
    | {
        readonly state: "delayed" | "dead-lettered";
        readonly delayMs: number;
        readonly failure: JobFailureMetadata;
      },
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.ts#L103)

## `events-store.types.ts`

Row shape returned when a consumer leases an event delivery.

### DeliveryRow (interface)

A leased delivery joined with its outbox envelope.

**Signature**

```ts
export interface DeliveryRow {
  readonly instance_id: string;
  readonly trigger_id: string;
  /** One-based attempt this lease runs. */
  readonly attempt: number;
  readonly envelope: UnknownEventEnvelope;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/events-store.types.ts#L5)

## `index.ts`

### "./database.types.js" (namespace export)

Re-exports all named exports from the "./database.types.js" module.

**Signature**

```ts
export * from "./database.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L1)

### "./events-provider.types.js" (namespace export)

Re-exports all named exports from the "./events-provider.types.js" module.

**Signature**

```ts
export * from "./events-provider.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L7)

### "./jobs-runtime.types.js" (namespace export)

Re-exports all named exports from the "./jobs-runtime.types.js" module.

**Signature**

```ts
export * from "./jobs-runtime.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L3)

### ClaimedOccurrence

One occurrence this pass enqueued (or skipped under `overlap: "skip"`).

**Signature**

```ts
export interface ClaimedOccurrence {
  readonly scheduleId: string;
  readonly occurrenceAt: string;
  /** The enqueued run, or `skipped` when an earlier run of the schedule was still active. */
  readonly runId: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-tick.ts#L20)

### PostgresJobWorker

Pull worker plus a close operation for its heartbeats.

**Signature**

```ts
export interface PostgresJobWorker extends NativeTaskWorker {
  /** Stops heartbeats without settling held runs; their leases then expire. */
  readonly close: () => Promise<void>;
  /** Runs currently leased by this worker. */
  readonly active: () => readonly string[];
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-worker.ts#L25)

### createPostgresEventProvider

**Signature**

```ts
declare const createPostgresEventProvider: (
  options: PostgresEventProviderOptions,
) => PostgresEventProvider;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L6)

### createPostgresJobsRuntime

**Signature**

```ts
declare const createPostgresJobsRuntime: (
  options: PostgresJobsRuntimeOptions,
) => PostgresJobsRuntime;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L2)

### runtimeIntegration

**Signature**

```ts
declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/index.ts#L8)

## `integration.ts`

Runtime registrations the generated server uses to build the Postgres jobs
and events providers from `defineApp` profiles. Providers of one process that
point at the same database and namespace share one pool. The process role
comes from `RELKIT_WORKER_ROLE`: `worker` (the default) serves requests and
runs job workers, the scheduler and event consumers; `api` only serves
requests, submits jobs and publishes events, leaving the work to separate
worker-role instances.

### PostgresWorkerRole (type alias)

Whether this process only serves requests (`api`) or also runs background work (`worker`).

**Signature**

```ts
type PostgresWorkerRole = "api" | "worker";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/integration.ts#L17)

### runtimeIntegration

Registrations for the `postgres-job` and `postgres-event` adapters.

**Signature**

```ts
declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/integration.ts#L35)

### workerRole

Reads the process role.

**Throws**

TypeError for any other value.

**Example**

```ts
workerRole("api") === "api";
```

**Signature**

```ts
declare const workerRole: (value?: string | undefined) => PostgresWorkerRole;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/integration.ts#L28)

## `jobs-controls.ts`

Reads, lists and cancels job runs. Cancellation runs in a transaction that
locks the row, so the first terminal transition wins: a queued run becomes
cancelled at once, a running run records the request and its worker observes
it on the next lease heartbeat, and later requests on a terminal run report
`already-terminal`. Each function is a lazy Effect requiring the SQL client.

### PostgresRunNotFoundError (class)

No run with this ID exists in the operation's service.

**Signature**

```ts
declare class PostgresRunNotFoundError
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-controls.ts#L18)

### cancelRun

Applies the first cancellation transition under a row lock.

**Signature**

```ts
declare const cancelRun: (
  tables: PostgresTables,
  request: NativeCancelRequest,
  context: OperationContext,
) => Effect.Effect<
  RunCancellationReceipt,
  PostgresBackendError | PostgresRunNotFoundError,
  SqlClient.SqlClient
>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-controls.ts#L93)

### getRun

Reads one run in the operation's service.

**Signature**

```ts
declare const getRun: (
  tables: PostgresTables,
  runId: string,
  context: OperationContext,
) => Effect.Effect<
  RunSnapshot,
  PostgresBackendError | PostgresRunNotFoundError,
  SqlClient.SqlClient
>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-controls.ts#L32)

### listRuns

Lists runs newest first with keyset pagination.

**Signature**

```ts
declare const listRuns: (
  tables: PostgresTables,
  query: RunListQuery,
  context: OperationContext,
) => Effect.Effect<RunPage<RunSnapshot>, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-controls.ts#L52)

## `jobs-lease.ts`

Lease protocol for job runs. A worker claims the oldest due run with
`FOR UPDATE SKIP LOCKED`, so concurrent workers never claim the same row; a
claim stamps an owner token and an expiry that heartbeats extend. Every
settlement is fenced on the owner token, so a worker whose lease expired and
was re-claimed cannot overwrite the new attempt. Expired leases are claimable
again while attempts remain; exhausted ones end failed and dead-lettered.

### HeartbeatOutcome (type alias)

Result of extending a lease.

**Signature**

```ts
type HeartbeatOutcome = "held" | "cancel-requested" | "lost";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-lease.ts#L24)

### completeRun

Records success for a held lease; a run with a pending cancellation ends cancelled.

**Signature**

```ts
declare const completeRun: (
  tables: PostgresTables,
  runId: string,
  owner: string,
  output: JsonValue | undefined,
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-lease.ts#L94)

### failRun

Records a failed attempt: schedules the next attempt per policy, or ends the
run failed and dead-lettered when the budget is spent or the failure forbids retry.

**Signature**

```ts
declare const failRun: (
  tables: PostgresTables,
  runId: string,
  owner: string | undefined,
  error: object | JsonValue | Error | undefined,
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-lease.ts#L120)

### heartbeatRun

Extends a held lease and reports a pending cancellation.

**Signature**

```ts
declare const heartbeatRun: (
  tables: PostgresTables,
  runId: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<HeartbeatOutcome, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-lease.ts#L69)

### leaseRun

Ends expired runs that have no attempts left, then claims the next due run.

**Signature**

```ts
declare const leaseRun: (
  tables: PostgresTables,
  service: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<JobRunRow | undefined, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-lease.ts#L34)

## `jobs-loops.ts`

Background loops of the jobs runtime: the scheduler pass and, for processes
that run attempts without the generated server's job loop, worker loops that
lease, execute and settle runs. Loops are forked into the connection owner,
log and survive transient failures, and stop when the runtime closes.

### forkScheduler

Forks the scheduler loop.

**Signature**

```ts
declare const forkScheduler: (
  database: PostgresDatabase,
  service: string,
  claimant: string,
  pollIntervalMs: number,
) => BackgroundFiber;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-loops.ts#L61)

### forkWorkerLoop

Forks one worker loop that keeps executing runs and sleeps when idle.

**Signature**

```ts
declare const forkWorkerLoop: (
  database: PostgresDatabase,
  step: (signal: AbortSignal) => Promise<boolean>,
  pollIntervalMs: number,
) => BackgroundFiber;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-loops.ts#L93)

### loopContext

Builds the operation context used by loops that run outside a request.

**Signature**

```ts
declare const loopContext: (service: string, signal: AbortSignal) => OperationContext;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-loops.ts#L19)

### processNextRun

Leases and executes at most one run, settling it through the worker.

**Signature**

```ts
declare const processNextRun: (
  worker: PostgresJobWorker,
  executor: TaskExecutor,
  context: OperationContext,
) => Promise<boolean>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-loops.ts#L37)

## `jobs-observe.ts`

Run observation by polling: an initial snapshot frame, then an update frame
whenever the snapshot changes, until the run is terminal or the caller
aborts. Polling reads authoritative state, so no notification can be missed.

### observeRun

Observes one run.

**Signature**

```ts
declare const observeRun: (
  get: (runId: string, context: OperationContext) => Promise<RunSnapshot>,
  request: NativeWatchRequest,
  context: OperationContext,
  pollIntervalMs: number,
) => AsyncGenerator<RunWatchFrame<RunSnapshot>>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-observe.ts#L20)

## `jobs-retry-policy.ts`

Pure retry decisions for failed job attempts. It reads the task's declared
`policy.retry` (attempt budget, exponential backoff, optional full jitter)
from the stored submission and the failure's own `retry`/`afterMs` hints,
matching the local provider so a task behaves the same on both backends.

### failureOf

Normalizes a thrown task failure into the public error envelope.

**Signature**

```ts
declare const failureOf: (value: Error | JsonValue | object | undefined) => JobErrorEnvelope;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-retry-policy.ts#L18)

### maxAttempts

Reads the attempt budget declared by the task policy.

**Signature**

```ts
declare const maxAttempts: (policy: JsonValue | undefined) => number;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-retry-policy.ts#L43)

### retryDelay

Decides whether a failed attempt runs again and after how long.

**Signature**

```ts
declare const retryDelay: (
  policy: JsonValue | undefined,
  attempt: number,
  failure: JobErrorEnvelope,
  random?: () => number,
) => number | undefined;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-retry-policy.ts#L55)

## `jobs-rows.ts`

Maps job-run rows to the public jobs contract. The table stores five states;
`delayed` and `retrying` are derived from the eligibility time and attempt
count at read time, and dead-lettered failures carry a diagnostic code. Pure
functions only: callers own the SQL that produced the rows.

### DEAD_LETTER_CODE

Diagnostic code reported on failed runs that reached the dead-letter state.

**Signature**

```ts
declare const DEAD_LETTER_CODE: "RELKIT_JOB_DEAD_LETTERED";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L12)

### JobRunRow

One row of the job-runs table.

**Signature**

```ts
export interface JobRunRow {
  readonly run_id: string;
  readonly service: string;
  readonly scope: string;
  readonly job_id: string;
  readonly task_id: string;
  readonly task_version: string;
  readonly build_id: string;
  /** Stored state: queued, running, completed, failed or cancelled. */
  readonly status: "queued" | "running" | "completed" | "failed" | "cancelled";
  /** Attempts started so far; a leased run's current attempt. */
  readonly attempt: number;
  readonly input: JobWireEnvelope;
  readonly request: StoredRequest;
  readonly dedupe_key: string | null;
  readonly operation_id: string;
  readonly retry_of_run_id: string | null;
  readonly run_at: TimestampValue;
  readonly accepted_at: TimestampValue;
  readonly started_at: TimestampValue | null;
  readonly completed_at: TimestampValue | null;
  readonly lease_owner: string | null;
  readonly lease_expires_at: TimestampValue | null;
  readonly output: JsonValue | null;
  readonly error: JobErrorEnvelope | null;
  readonly cancellation: RunCancellationReceipt | null;
  readonly dead_lettered: boolean;
  /** Database time when the row was read, used for derived states such as `delayed`. */
  readonly observed_at: TimestampValue;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L30)

### StoredRequest

Submission metadata kept in the `request` jsonb column; every field is optional.

**Signature**

```ts
export interface StoredRequest {
  readonly inputHash?: string;
  readonly inputSchemaHash?: string;
  readonly acceptanceIdentity?: string;
  readonly occurrenceIdentity?: string;
  readonly idempotencyKey?: string;
  readonly policy?: JsonValue;
  readonly scheduledFor?: string;
  readonly scheduleId?: string;
  readonly tags?: readonly string[];
  readonly correlationId?: string;
  readonly parentRunId?: string;
  readonly propagation?: TracePropagation;
  readonly serviceGeneration?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L13)

### TimestampValue

A timestamp column as the driver returns it.

**Signature**

```ts
type TimestampValue = Date | string;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L10)

### handleOf

Builds the acceptance handle returned by submission and retry.

**Signature**

```ts
declare const handleOf: (row: JobRunRow, duplicate?: boolean) => RunHandle;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L29)

### isTerminal

Reports whether a stored state can still change.

**Signature**

```ts
declare const isTerminal: (status: JobRunRow["status"]) => boolean;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L115)

### iso

Normalizes a driver timestamp to ISO-8601 text.

**Signature**

```ts
declare const iso: (value: TimestampValue) => string;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L19)

### snapshotOf

Projects one row to the public run snapshot.

**Signature**

```ts
declare const snapshotOf: (row: JobRunRow) => RunSnapshot;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L58)

### statusOf

Derives the public run status from the stored state and eligibility time.

**Signature**

```ts
declare const statusOf: (row: JobRunRow) => RunSnapshot["status"];
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.ts#L46)

## `jobs-rows.types.ts`

Row shapes read from the job-runs table and the submission metadata persisted with each run.

### JobRunRow (interface)

One row of the job-runs table.

**Signature**

```ts
export interface JobRunRow {
  readonly run_id: string;
  readonly service: string;
  readonly scope: string;
  readonly job_id: string;
  readonly task_id: string;
  readonly task_version: string;
  readonly build_id: string;
  /** Stored state: queued, running, completed, failed or cancelled. */
  readonly status: "queued" | "running" | "completed" | "failed" | "cancelled";
  /** Attempts started so far; a leased run's current attempt. */
  readonly attempt: number;
  readonly input: JobWireEnvelope;
  readonly request: StoredRequest;
  readonly dedupe_key: string | null;
  readonly operation_id: string;
  readonly retry_of_run_id: string | null;
  readonly run_at: TimestampValue;
  readonly accepted_at: TimestampValue;
  readonly started_at: TimestampValue | null;
  readonly completed_at: TimestampValue | null;
  readonly lease_owner: string | null;
  readonly lease_expires_at: TimestampValue | null;
  readonly output: JsonValue | null;
  readonly error: JobErrorEnvelope | null;
  readonly cancellation: RunCancellationReceipt | null;
  readonly dead_lettered: boolean;
  /** Database time when the row was read, used for derived states such as `delayed`. */
  readonly observed_at: TimestampValue;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L30)

### StoredRequest (interface)

Submission metadata kept in the `request` jsonb column; every field is optional.

**Signature**

```ts
export interface StoredRequest {
  readonly inputHash?: string;
  readonly inputSchemaHash?: string;
  readonly acceptanceIdentity?: string;
  readonly occurrenceIdentity?: string;
  readonly idempotencyKey?: string;
  readonly policy?: JsonValue;
  readonly scheduledFor?: string;
  readonly scheduleId?: string;
  readonly tags?: readonly string[];
  readonly correlationId?: string;
  readonly parentRunId?: string;
  readonly propagation?: TracePropagation;
  readonly serviceGeneration?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L13)

### TimestampValue (type alias)

A timestamp column as the driver returns it.

**Signature**

```ts
type TimestampValue = Date | string;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-rows.types.ts#L10)

## `jobs-runtime.ts`

Assembles the Postgres jobs adapter: durable submission, reads, cancellation
and retry over the job-runs table, a pull worker with leases, persisted
schedules with a once-per-occurrence scheduler, and optional in-process
worker loops. The generated server drives `worker` from its job loop in the
`worker` role and calls `registerWorker`, which starts the scheduler unless
the instance runs in the `api` role.

### "./jobs-runtime.types.js" (namespace export)

Re-exports all named exports from the "./jobs-runtime.types.js" module.

**Signature**

```ts
export * from "./jobs-runtime.types.js";
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.ts#L25)

### createPostgresJobsRuntime

Creates the Postgres jobs runtime.

**Throws**

TypeError when neither `url` nor `database` is given.

**Example**

```ts
const jobs = createPostgresJobsRuntime({ url: process.env.DATABASE_URL! });
```

**Signature**

```ts
declare const createPostgresJobsRuntime: (
  options: PostgresJobsRuntimeOptions,
) => PostgresJobsRuntime;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.ts#L34)

## `jobs-runtime.types.ts`

Contracts of the Postgres jobs runtime: construction options, worker registration and the runtime surface.

### PostgresFaults (interface)

Faults a test can inject at the provider boundary.

**Signature**

```ts
export interface PostgresFaults {
  /** Commit submissions but report their outcome as unknown, as after a lost response. */
  readonly loseSubmitResponse?: boolean;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L13)

### PostgresJobsRuntime (interface)

The Postgres jobs adapter plus its worker, scheduler and loop controls.

**Signature**

```ts
export interface PostgresJobsRuntime extends JobsAdapterRuntime {
  readonly database: PostgresDatabase;
  readonly worker: PostgresJobWorker;
  readonly schedules: NativeScheduleOperations;
  readonly registerWorker: (options: PostgresWorkerRegistration) => PostgresWorkerHandle;
  /** Runs one scheduler pass now. */
  readonly tickSchedules: () => Promise<readonly ClaimedOccurrence[]>;
  /** Starts the background scheduler loop; idempotent. */
  readonly startScheduler: () => void;
  /** Starts background loops that lease and execute runs in this process. */
  readonly startWorkers: (options: PostgresWorkerLoopOptions) => void;
  /** Leases and executes at most one run; resolves true when one ran. */
  readonly processNext: (executor: TaskExecutor) => Promise<boolean>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L68)

### PostgresJobsRuntimeOptions (interface)

Options for `createPostgresJobsRuntime`.

**Signature**

```ts
export interface PostgresJobsRuntimeOptions extends Partial<PostgresDatabaseOptions> {
  /** Shared connection owner; when given, `url` is ignored and `close()` leaves it open. */
  readonly database?: PostgresDatabase;
  /** Jobs service (profile) name; defaults to `postgres`. */
  readonly service?: string;
  /** Lease duration in ms; defaults to 30 000. */
  readonly leaseMs?: number;
  /** Idle polling interval for the scheduler and worker loops in ms; defaults to 1 000. */
  readonly pollIntervalMs?: number;
  /** Prefix of owner tokens and occurrence claims; defaults to a random instance ID. */
  readonly workerId?: string;
  /** Test-only fault injection. */
  readonly faults?: PostgresFaults;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L19)

### PostgresTaskDefinition (interface)

A task binding the generated server registers for each job.

**Signature**

```ts
export interface PostgresTaskDefinition {
  readonly jobId: string;
  readonly taskId: string;
  readonly taskVersion?: string;
  readonly version?: string;
  readonly buildId: string;
  readonly policy?: JsonValue;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L35)

### PostgresWorkerHandle (interface)

Handle the generated server awaits and closes.

**Signature**

```ts
export interface PostgresWorkerHandle {
  readonly definitions: readonly PostgresTaskDefinition[];
  readonly ready: () => Promise<void>;
  readonly close: () => Promise<void>;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L53)

### PostgresWorkerLoopOptions (interface)

Options for running task attempts in this process without the generated server.

**Signature**

```ts
export interface PostgresWorkerLoopOptions {
  /** Executes one envelope; the generated server passes its task executor. */
  readonly executor: TaskExecutor;
  /** Concurrent attempts; defaults to 1. */
  readonly concurrency?: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L60)

### PostgresWorkerRegistration (interface)

Arguments of `registerWorker`, matching what the generated server passes.

**Signature**

```ts
export interface PostgresWorkerRegistration {
  readonly definitions: readonly PostgresTaskDefinition[];
  readonly executor: TaskExecutor;
  /** False in the `api` role: this instance only submits, and runs no scheduler. */
  readonly startWorker?: boolean;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-runtime.types.ts#L45)

## `jobs-submit.ts`

Durable submission and retry for the job-runs table. A submission is one
INSERT whose dedupe key (job, idempotency key, occurrence) is unique per
service and scope, so concurrent duplicates resolve to the first run. A retry
copies a terminal run into a new run linked by `retry_of_run_id`; the retry
identity is unique per original run, so repeating a retry returns the same
new run. Each function is a lazy Effect requiring the SQL client.

### dedupeKey

Builds the submission dedupe key; runs without an idempotency key or occurrence never deduplicate.

**Signature**

```ts
declare const dedupeKey: (request: NativeSubmission) => string | null;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-submit.ts#L29)

### retryRun

Creates (or returns) the new run for one retry of a terminal run.

**Signature**

```ts
declare const retryRun: (
  tables: PostgresTables,
  request: NativeRetryRequest,
  context: OperationContext,
) => Effect.Effect<
  {
    retryOfRunId: string;
    accepted: true;
    runId: string;
    jobId: string;
    taskId: string;
    taskVersion: string;
    acceptedAt: string;
    duplicate?: boolean;
    idempotencyExpiresAt?: string;
  },
  PostgresBackendError,
  SqlClient.SqlClient
>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-submit.ts#L106)

### storedRequest

Collects the submission metadata persisted in the `request` column.

**Signature**

```ts
declare const storedRequest: (
  request: NativeSubmission,
  context: OperationContext,
) => StoredRequest;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-submit.ts#L44)

### submitRun

Inserts a run, or returns the run that already owns its dedupe key.

**Signature**

```ts
declare const submitRun: (
  tables: PostgresTables,
  request: NativeSubmission,
  context: OperationContext,
) => Effect.Effect<RunHandle, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-submit.ts#L72)

### unknownSubmission

Describes a write whose commit may have happened but whose response was lost.

**Signature**

```ts
declare const unknownSubmission: (request: NativeSubmission) => NativeReceipt;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-submit.ts#L142)

## `jobs-work.ts`

Builds the execution envelope and binding the task executor receives for a
leased run. The binding's signal belongs to the lease: the worker aborts it
when a cancellation is requested or the lease is lost. Pure construction; the
worker owns the controller and heartbeat.

### bindingOf

Builds the binding for one attempt.

**Signature**

```ts
declare const bindingOf: (
  row: JobRunRow,
  signal: AbortSignal,
  context: OperationContext,
) => TaskExecutionBinding;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-work.ts#L53)

### envelopeOf

Projects a leased row to the executor envelope.

**Signature**

```ts
declare const envelopeOf: (row: JobRunRow) => TaskExecutionEnvelope;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-work.ts#L20)

## `jobs-worker.ts`

Pull worker for the Postgres jobs backend. `next` claims one due run with a
fresh owner token and starts a heartbeat fiber that extends the lease every
third of its duration; the heartbeat aborts the attempt's signal when a
cancellation is requested or the lease is lost. `complete` and `fail` stop
the heartbeat and settle fenced on the owner token. Closing the worker stops
heartbeats without settling, which is exactly what a crash looks like to the
database: the lease expires and another worker retries the run.

### PostgresJobWorker (interface)

Pull worker plus a close operation for its heartbeats.

**Signature**

```ts
export interface PostgresJobWorker extends NativeTaskWorker {
  /** Stops heartbeats without settling held runs; their leases then expire. */
  readonly close: () => Promise<void>;
  /** Runs currently leased by this worker. */
  readonly active: () => readonly string[];
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-worker.ts#L25)

### createPostgresJobWorker

Creates the pull worker for one jobs service.

**Signature**

```ts
declare const createPostgresJobWorker: (
  database: PostgresDatabase,
  options: { readonly service: string; readonly leaseMs: number; readonly workerId: string },
) => PostgresJobWorker;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/jobs-worker.ts#L38)

## `schedule-time.ts`

Pure occurrence arithmetic for persisted schedules. Cron schedules use
Effect's `Cron` with the schedule's IANA timezone; interval schedules advance
from the previous occurrence so they do not drift with polling. The misfire
policy decides which due occurrences are enqueued after downtime.

### MAX_CATCH_UP

Upper bound of occurrences enqueued in one pass for `misfire: "all"`.

**Signature**

```ts
declare const MAX_CATCH_UP: 100;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedule-time.ts#L14)

### ON_TIME_MS

How far behind an occurrence may be and still count as on time for `misfire: "skip"`.

**Signature**

```ts
declare const ON_TIME_MS: 60000;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedule-time.ts#L12)

### ScheduleTiming (interface)

Timing fields of a stored schedule definition.

**Signature**

```ts
export interface ScheduleTiming {
  readonly cron?: string;
  readonly timezone?: string;
  readonly every?: JsonValue;
  readonly misfire?: "skip" | "latest" | "all";
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedule-time.ts#L17)

### dueOccurrences

Selects the occurrences to enqueue now and the next pending occurrence.

**Signature**

```ts
declare const dueOccurrences: (
  timing: ScheduleTiming,
  nextAt: Date,
  now: Date,
) => { readonly due: readonly Date[]; readonly next: Date };
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedule-time.ts#L45)

### nextOccurrence

Computes the first occurrence strictly after an instant.

**Throws**

TypeError when the timing is neither a valid cron nor a positive interval.

**Signature**

```ts
declare const nextOccurrence: (timing: ScheduleTiming, after: Date) => Date;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedule-time.ts#L31)

## `schedules-store.ts`

Persisted schedule definitions behind the native schedule operations that
schedule reconciliation and the admin API call. Each row keeps the authored
definition (with its ownership metadata), the submission template the
scheduler uses to enqueue runs, and the next pending occurrence. Upserting a
definition with unchanged timing keeps its pending occurrence, so restarts
and redeploys neither skip nor repeat one.

### createScheduleOperations

Builds the native schedule operations for one jobs service.

**Signature**

```ts
declare const createScheduleOperations: (
  database: PostgresDatabase,
  service: string,
  template: (jobId: string) => Omit<ScheduleSubmission, "scope"> | undefined,
) => NativeScheduleOperations;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-store.ts#L29)

## `schedules-tick.ts`

Enqueues schedule occurrences exactly once across instances. One pass locks
due schedule rows with `FOR UPDATE SKIP LOCKED`, claims each occurrence by
inserting into the occurrences table, whose primary key is (service,
schedule, occurrence time), enqueues the run in the same transaction, and
advances the pending occurrence. A contender that reads a stale pending
occurrence loses on the primary key, so it never enqueues a second run.

### ClaimedOccurrence (interface)

One occurrence this pass enqueued (or skipped under `overlap: "skip"`).

**Signature**

```ts
export interface ClaimedOccurrence {
  readonly scheduleId: string;
  readonly occurrenceAt: string;
  /** The enqueued run, or `skipped` when an earlier run of the schedule was still active. */
  readonly runId: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-tick.ts#L20)

### claimOccurrence

Claims one occurrence and enqueues its run; a lost race on the primary key claims nothing.

**Signature**

```ts
declare const claimOccurrence: (
  tables: PostgresTables,
  row: ScheduleRow,
  occurrenceAt: string,
  claimant: string,
) => Effect.Effect<
  { scheduleId: string; occurrenceAt: string; runId: string } | undefined,
  PostgresBackendError,
  SqlClient.SqlClient
>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-tick.ts#L96)

### occurrenceIdentity

Builds the identity that ties a run to its occurrence.

**Signature**

```ts
declare const occurrenceIdentity: (scheduleId: string, occurrenceAt: string) => string;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-tick.ts#L33)

### tickSchedules

Runs one scheduler pass for a jobs service.

**Signature**

```ts
declare const tickSchedules: (
  tables: PostgresTables,
  service: string,
  claimant: string,
) => Effect.Effect<Array<ClaimedOccurrence>, PostgresBackendError, SqlClient.SqlClient>;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules-tick.ts#L44)

## `schedules.types.ts`

Row and template shapes for persisted schedules and their claimed occurrences.

### ScheduleRow (interface)

One row of the schedules table.

**Signature**

```ts
export interface ScheduleRow {
  readonly service: string;
  readonly schedule_id: string;
  readonly job_id: string;
  /** Authored definition including reconciliation ownership metadata. */
  readonly definition: JsonValue;
  readonly submission: ScheduleSubmission;
  readonly state: "active" | "paused" | "deleted";
  /** Earliest occurrence not yet claimed. */
  readonly next_at: TimestampValue;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules.types.ts#L16)

### ScheduleSubmission (interface)

The task binding a scheduler needs to enqueue a run without the application code.

**Signature**

```ts
export interface ScheduleSubmission {
  readonly jobId: string;
  readonly taskId: string;
  readonly taskVersion: string;
  readonly buildId: string;
  readonly scope: string;
  readonly policy?: JsonValue;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/runtime/schedules.types.ts#L6)

## `schema.ts`

Owns the Postgres backend's table layout: identifier validation, quoted table
names, and the idempotent DDL that the runtime applies at startup under an
advisory lock. Applications that own their migrations can apply the same
statements from `postgresBackendSql`. Nothing here opens a connection.

### PostgresTableOptions

Where the backend's tables live; both names are validated SQL identifiers.

**Signature**

```ts
export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L4)

### PostgresTables

Fully qualified, quoted table names for one backend namespace.

**Signature**

```ts
export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L12)

### postgresBackendSql

Lists the idempotent DDL statements for one backend namespace, in apply order.

**Example**

```ts
postgresBackendSql().length > 0;
```

**Signature**

```ts
declare const postgresBackendSql: (options?: PostgresTableOptions) => readonly string[];
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.ts#L41)

### postgresTables

Resolves quoted table names for one backend namespace.

**Throws**

TypeError when a name is not a lowercase identifier of at most 41 characters.

**Example**

```ts
postgresTables({ tablePrefix: "app" }).jobRuns === '"public"."app_job_runs"';
```

**Signature**

```ts
declare const postgresTables: (options?: PostgresTableOptions) => PostgresTables;
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.ts#L19)

## `schema.types.ts`

Where the backend's tables live; both names are validated SQL identifiers.

### PostgresTableOptions (interface)

Where the backend's tables live; both names are validated SQL identifiers.

**Signature**

```ts
export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L4)

### PostgresTables (interface)

Fully qualified, quoted table names for one backend namespace.

**Signature**

```ts
export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}
```

[Source](https://github.com/rel-kit/relkit/blob/main/integrations/packages/postgres/src/schema.types.ts#L12)
