# @makerx/blob-data-streamer

An in-process blob-storage-backed streaming broker — at-least-once, ordered, single-producer-per-topic. Cheap to run, simple to deploy. Runs on **Azure Blob Storage** or **AWS S3** behind one provider-neutral interface.

## What it is, in one paragraph

A TypeScript library that turns Azure Blob Storage or AWS S3 into an in-process, at-least-once, ordered, CDC-style streaming bus with infinite durability and low running cost. The **producer** is your own process, embedding the library; it holds a blob lease that fences it as the single writer for a topic. **Consumers** are also embedded; consumer groups share a lease-protected offset blob to elect a single active reader per group. **Postgres is an optional add-on** — it carries `LISTEN/NOTIFY` wake-up signals when sub-second latency matters; otherwise consumers poll cheaply via `HEAD` requests. **Sealed segments** (older parts of the stream that are immutably archived) are block blobs in both JSONL (committed records) and Parquet (analytical) variants, both verified via sha256 + row count before being published in the segment index — enabling efficient replay and analytics of the historical stream.

## Install

The core package carries **no cloud SDK** — install the one for the backend you
target (they are **optional peer dependencies**, ADR-0026), and import that
backend's provider from its subpath:

```bash
# Azure Blob Storage
npm install @makerx/blob-data-streamer @azure/storage-blob

# AWS S3
npm install @makerx/blob-data-streamer @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
```

| Target | Install | Provider import |
| --- | --- | --- |
| Azure Blob | `@azure/storage-blob` | `import { azureBlobProvider } from '@makerx/blob-data-streamer/azure'` |
| AWS S3 | `@aws-sdk/client-s3` + `@aws-sdk/s3-request-presigner` | `import { s3BlobProvider } from '@makerx/blob-data-streamer/s3'` |

You build the SDK client yourself (so you control credentials — connection
string, SAS, `DefaultAzureCredential` / managed identity for Azure;
`fromNodeProviderChain`, IRSA / IAM-role / web-identity for S3) and pass it into
the provider; the broker never sees the underlying credential. An Azure-only app
never installs the AWS SDK, and vice versa.

If you opt in to compaction (`compaction.enabled: true` on `Producer.start`), also install:

```bash
npm install @duckdb/node-api
```

DuckDB — via the `@duckdb/node-api` ("Node Neo") client, which ships prebuilt binaries with no node-gyp build (ADR-0021) — converts sealed JSONL segments to Parquet siblings. The library tolerates DuckDB being missing: compaction is off by default, and with compaction on, Parquet conversion degrades to JSONL-only if `@duckdb/node-api` is absent.

> [!IMPORTANT]
> **Parquet compaction to Azure needs a CA bundle where DuckDB's `azure` extension looks for it.** The extension statically links its own libcurl, which searches distro-specific CA paths — **not** Node's CA store. On a slim/Debian image (e.g. `node:lts-slim`), Azure blob TLS then fails with `Problem with the SSL CA cert (path? access rights?)` and **no Parquet siblings are produced** (JSONL archives are unaffected, so it can go unnoticed). This is a documented DuckDB-extension behaviour, not a bug in this library — see the [DuckDB Azure extension docs](https://duckdb.org/docs/stable/core_extensions/azure) and duckdb/duckdb [#9133](https://github.com/duckdb/duckdb/issues/9133) / [#9675](https://github.com/duckdb/duckdb/discussions/9675). Fix it in your **deployment image** by making the bundle resolvable, e.g. on Debian:
>
> ```dockerfile
> RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \
>   && mkdir -p /etc/pki/tls/certs \
>   && ln -sf /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt
> ```
>
> (Some builds instead honour `CURL_CA_INFO`/`CURL_CA_PATH` when the extension uses its `curl` transport; the DuckDB docs cover both routes. The exact path a given `@duckdb/node-api` build expects can vary — verify against your version.)
>
> Separately, native segfaults have been reported in this stack (`@duckdb/node-api` + `azure` extension reading `az://`, e.g. duckdb/duckdb-node-neo [#154](https://github.com/duckdb/duckdb-node-neo/issues/154), architecture-specific, unresolved). Because the conversion runs native code, the compactor isolates it in a child process (ADR-0028) so such a crash degrades to a JSONL-only archive instead of taking the host process down.

If you want sub-second consumer wake-up via Postgres `LISTEN/NOTIFY`, install `pg` and `pg-listen`. Otherwise consumers poll cheap `HEAD` requests against the active blob.

## Producer quickstart

The producer is embedded in *your* process — there is no broker service. `Producer.start()` acquires the lease on `current-N.jsonl` for `(tenant, topic)`; that lease is what fences this process as the single writer. If another producer holds the lease, `start()` waits about the lease TTL + 5 s (≈ 65 s by default, so a crashed predecessor's lease can expire), then rejects with `LeaseAlreadyHeldError` and your orchestrator (Kubernetes, systemd, ACA) decides whether to retry.

```ts
import { BlobServiceClient } from '@azure/storage-blob';
import { Producer } from '@makerx/blob-data-streamer';
import { azureBlobProvider } from '@makerx/blob-data-streamer/azure';

const serviceClient = BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING!);
await serviceClient.getContainerClient('streams').createIfNotExists();

const storage = azureBlobProvider({ serviceClient, containerName: 'streams' });
// On S3 instead:
//   import { S3Client } from '@aws-sdk/client-s3';
//   import { s3BlobProvider } from '@makerx/blob-data-streamer/s3';
//   const storage = s3BlobProvider({ client: new S3Client({ region }), bucketName: 'streams' });
// The Producer/Consumer code below is identical regardless of backend.

const producer = await Producer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
});

// `send` resolves when the record is durable on Azure Blob (after the
// coalesced AppendBlock that includes it commits). `offset` is the
// broker-assigned position in the topic.
for (let i = 0; i < 5; i++) {
  const { offset } = await producer.send({
    id: `order-${i}`,                                  // your idempotency key
    body: JSON.stringify({ amount: 100 + i }),         // string, opaque to the broker
  });
  console.log(`durable at offset ${offset}`);
}

// Graceful shutdown — flushes any in-flight batch and releases the lease.
await producer.close();
```

**`record.id`** is yours — pick something stable per logical event so consumers can dedupe on it. **`record.body`** is an opaque string the broker round-trips; binary payloads should be base64-encoded by you.

**Single producer per topic, permanently.** This is enforced by the blob lease and is a hard architectural constraint. If you need multiple writers, write to multiple topics and fan-in at the consumer.

**Atomic batches** — `sendBatch` writes an array of records all or nothing, in order, and returns their offsets. `openBatch` is the streaming form for batches you don't want in memory at once. A batch holds the producer's write slot until it commits or aborts; other `send()` calls queue behind it.

```ts
const { offsets, batchId } = await producer.sendBatch(records, { batchId: 'tx-123' }); // batchId optional

const batch = await producer.openBatch({ batchId: 'tx-124' });
await batch.append(firstChunk);   // writes full blocks as they fill; nothing is delivered yet
await batch.append(secondChunk);
const { offsets: [first, last], count } = await batch.commit(); // or batch.abort()
```

Consumers see the batch id as `record.batchId`. Limits:

- A batch that fits one append block (`maxBatchBytes`, default 3 MiB) needs no extra options.
- A larger batch needs `allowMultiBlockBatches: true` (Azure only; otherwise `BatchTooLargeError`). It is delivered only once committed; an aborted batch leaves an offset gap and is never delivered. **Multi-block batches change the wire format: upgrade every reader of the topic to ≥ 0.5.0 before enabling them.**
- `sendBatch` is capped by `maxSendBatchBytes` (default 64 MiB).
- An open batch with no `append` for `batchIdleTimeoutMs` (default 60 s) is aborted.
- `close()` lets an in-flight `sendBatch`, and `sendBatch` calls already queued, run to commit. It aborts a batch still open through an `openBatch` handle and refuses an `openBatch` still waiting for the write slot.

See [ADR-0030](../../docs/adr/0030-atomic-batch-append-safe-outcomes-and-rollover-recovery.md).

**`AppendOutcomeUnknownError`** — if an append fails and the producer can't tell whether it landed, the affected `send()` / batch rejects with this error and the producer closes. The records may have been written: restart the producer, then reconcile with `Consumer.replay` from `err.firstOffset`, matching by batch id or your own record ids.

**Optional Postgres NOTIFY signal layer** — wire it when sub-second consumer wake-up matters. Without it, consumers poll cheap `HEAD` requests:

```ts
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const producer = await Producer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
  postgres: { pool, leaderId: process.env.HOSTNAME }, // leaderId is diagnostic only
});
```

If you wire the NOTIFY layer, apply the schema migration once at startup (see [`applyMigrations`](#applying-the-postgres-schema-once)).

## Consumer quickstart

The consumer is also embedded in *your* process. `Consumer.start()` acquires the lease on `.consumer_groups/<group>.offset`; within a consumer group exactly one consumer is active at a time, and the others (standbys started elsewhere) block waiting on the lease. When the active consumer's process dies, the lease expires and a standby takes over from the last committed offset.

```ts
import { BlobServiceClient } from '@azure/storage-blob';
import { Consumer } from '@makerx/blob-data-streamer';
import { azureBlobProvider } from '@makerx/blob-data-streamer/azure';

const serviceClient = BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING!);
const storage = azureBlobProvider({ serviceClient, containerName: 'streams' });

const consumer = await Consumer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
  consumerGroup: 'fulfilment',     // change this string to fan out a parallel projection
  handler: async (record) => {
    const order = JSON.parse(record.body);

    // 1. await EVERY downstream side-effect to durable completion BEFORE returning.
    //    The broker commits offsets after handler resolves; if you return early
    //    and crash, the offset advances past a record whose side-effect was lost.
    // 2. Be idempotent on record.id — up to `commitEveryN - 1` records can be
    //    re-dispatched per consumer restart. UPSERT, outbox, idempotency table,
    //    pick one.
    await upsertOrderInDb(record.id, order);
  },
});

// On shutdown — flushes pending offset commit + releases the lease.
process.on('SIGTERM', async () => {
  await consumer.close();
  process.exit(0);
});
```

**At-least-once contract** — the broker guarantees every produced record is dispatched to the handler at least once. Duplicates can happen on consumer restart, lease handover, or replay. Your handler MUST be idempotent on `record.id`. Full contract on the `ConsumerHandler` JSDoc in the source.

**Batch handler** — when your sink is much cheaper per call with many records (Kafka produce, bulk insert), pass `batchHandler` instead of `handler`. The two are mutually exclusive.

```ts
const consumer = await Consumer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
  consumerGroup: 'kafka-projection',
  maxBatchRecords: 500, // default 500
  batchHandler: async (records) => {
    // Resolve only when the WHOLE batch is durable downstream.
    await kafkaProducer.send({ topic: 'orders', messages: records.map((r) => ({ key: r.id, value: r.body })) });
  },
});
```

Records arrive in offset order, at most `maxBatchRecords` per call. A batch holds only records already read, so the consumer never waits to fill one: at low volume a batch is often a single record. If the handler rejects, nothing in the batch advances and the whole batch is retried (`handlerRetry` backoff; after the retry budget every record of the batch is dead-lettered). `commitEveryN` still counts records, but commits happen only after a batch resolves, so an offset commit never covers a batch that has not resolved. After a crash up to `commitEveryN - 1 + maxBatchRecords` records can be delivered again. `Consumer.replay` stays per-record. Full contract on the `ConsumerBatchHandler` JSDoc and [ADR-0029](../../docs/adr/0029-opt-in-consumer-batch-handler.md).

**Reading the full stream externally** — `Consumer.getStreamManifest()` returns the ordered list of files (sealed Parquet/JSONL segments + the live tail), each with a read SAS URL, so a BI tool or bulk job can read the whole stream without running a consumer. Lease-free; no consumer group required.

```ts
const manifest = await Consumer.getStreamManifest({ storage, tenant: 'acme', topic: 'orders' });
for (const f of manifest.files) {
  // f.format ('parquet' | 'jsonl'), f.url (read SAS or null), f.startOffset / f.endOffset, f.volatile (live tail may still grow)
  console.log(f.format, f.url);
}
```

Pass `format: 'parquet-only'` for an analytics-only view, or best-effort `fromTimestamp` / `toTimestamp` to narrow by producer emission time — the result is a file-level superset, so filter records by `ts` after reading. See [ADR-0022](../../docs/adr/0022-stream-read-manifest-and-best-effort-seek-by-date.md).

Archived (sealed) files hold no open, aborted or abandoned batches. An invalid batch (only corruption makes one) is kept verbatim, `bm` and `_commit` included, so protocol-aware readers apply their poison policy to it. A raw JSONL reader must skip a range from a `bm` frame to its `_commit` whose count or offsets do not match the frames between them, or read the Parquet sibling, which leaves invalid batches out. The live tail and pending seals are the raw `current-N` blobs: a raw reader may rarely see records of an open or aborted multi-block batch there (frames tagged `b`, followed by an `_abort` or no `_commit` yet). Read through `Consumer` or `Consumer.replay` if that matters.

**Polling vs NOTIFY:**

- **Polling (default)** — consumer issues a cheap `HEAD` on `current-N.jsonl` every `pollIntervalMs` (default 1 000 ms). Latency floor ≈ `pollIntervalMs / 2`. No Postgres needed.
- **NOTIFY** — wire Postgres + apply migrations + pass `postgres.connection` as either a connection string or a `pg.ClientConfig`. p50 latency drops to ~150 ms. Falls back to polling automatically if Postgres reconnects or NOTIFY is lost.

```ts
// Static credentials (local dev / containers):
const consumer = await Consumer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
  consumerGroup: 'fulfilment',
  postgres: { connection: process.env.DATABASE_URL! },
  handler,
});

// Managed identity (Azure AAD) — pass a ClientConfig with a token-refreshing
// password function. `pg-listen` (used internally) keeps a dedicated long-lived
// connection for LISTEN, so this is NOT a `pg.Pool`.
const credential = new DefaultAzureCredential();
const consumer = await Consumer.start({
  storage,
  tenant: 'acme',
  topic: 'orders',
  consumerGroup: 'fulfilment',
  postgres: {
    connection: {
      host: 'mydb.postgres.database.azure.com',
      user: 'mydb-app',
      database: 'mydb',
      password: async () =>
        (await credential.getToken('https://ossrdbms-aad.database.windows.net')).token,
      ssl: { rejectUnauthorized: true },
    },
  },
  handler,
});
```

**We recommend you stay at a minimum on the broker's default `pollIntervalMs` (1 000 ms).** Aggressive polling creates HEAD/range-read contention with producer writes — measured to inflate p99 by 5× at 4 k evt/s. Running costs also increase the more frequently you poll.

## Applying the Postgres schema once

Only needed when you use the NOTIFY signal layer. Run once at startup (idempotent — subsequent calls no-op):

```ts
import { Pool } from 'pg';
import { applyMigrations } from '@makerx/blob-data-streamer';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
await applyMigrations({ pool });
// ... now safe to construct producers/consumers with `postgres: { pool }`.
```

For managed identity / AAD, build the pool with `password: async () => token` and pass that pool through — the library borrows a client and inherits the auth. See the `applyMigrations` JSDoc for the AAD example. `schemaName` defaults to `streams`; pass a different one to both `applyMigrations` and the `postgres.schemaName` option on `Producer.start` if you need to avoid a collision.

`node-pg-migrate` is an **optional peer dependency** — install it only if you call `applyMigrations`:

```bash
npm install node-pg-migrate
```

## When to use it / when not

This library targets SMB-to-mid-rate workloads where Kafka is overkill or unaffordable. Real-Azure-measured envelope on a **2 vCPU / 4 GiB ACA Consumption replica** in `australiaeast` against `Standard_LRS` storage:

| Band | Aggregate rate | `sendToAck` p50 / p99 | Polling e2e p99 | NOTIFY e2e p50 / p99 |
| --- | --- | --- | --- | --- |
| **SMB** | ≤ 500 evt/s | < 50 ms / < 500 ms | < 2 s | < 500 ms / < 2 s |
| **Mid-rate** | 500 – 20 000 evt/s | < 50 ms / < 500 ms | < 2 s | n/a (polling wins above 4 k/s) |
| **Analytics-class** | > 20 000 evt/s | < 500 ms / < 3 s | < 10 s | n/a |

Single 2 vCPU host caps at ~30–50 k evt/s aggregate (event-loop CPU bound, not Azure-throttling). Above that, scale out via separate containers per producer+consumer pair for the full envelope.

The numbers above are the **Azure**-measured envelope. The S3 backend's append latency is flat regardless of segment size (immutable byte-offset-keyed parts, ADR-0023); its end-to-end throughput/latency envelope under the real broker is being characterised by the comprehensive S3 run and will be published in `docs/performance.md`.

**Use when:**
- Aggregate < 20 k evt/s and you want Kafka-style semantics without cost and overhead of operating Kafka.
- You need single-producer-per-topic at the application layer.
- At-least-once + idempotent handlers fit your downstream model.
- Azure Blob **or** AWS S3 is your durable substrate (one provider-neutral interface; pick per deployment).

**Do not use when:**
- You need exactly-once cross-topic transactional semantics.
- You need multi-producer-per-topic fan-in (architecturally out of scope).
- You need GDPR record-level deletion of historic events (append-only by design — crypto-shredding is the recommended workaround, not yet shipped).
- You need a Kafka wire-protocol — this is a bespoke library, not a Kafka clone.

## Production checklist

1. **Build your `BlobServiceClient` with managed identity** wherever possible — the broker never sees the credential, so token rotation and IAM policies live in your hands.
2. **Pick a deployment shape** based on your aggregate rate. Recommended starting point: SMB scale runs in-process; mid-rate N≥5 runs single-container role-split via `child_process.spawn`; above ~8 k/s/pair or > 20 k/s aggregate, scale out across containers.
3. **Default `pollIntervalMs` (1 000 ms) is correct** for almost every workload. Aggressive polling creates HEAD/range-read contention with producer writes. Leave it alone unless you need < 500 ms freshness and Postgres NOTIFY is not an option.
4. **Opt in to compaction** (`Producer.start({ compaction: { enabled: true } })`) when you want sealed JSONL + Parquet archive on Azure for replay and analytics. Off by default so SDK callers don't get a background `setInterval` worker they didn't ask for.
5. **Make your handler idempotent** on `record.id`. UPSERT, outbox, idempotency table — pick one. The broker re-dispatches up to `commitEveryN - 1` records on consumer restart.
6. **Wire OTel.** `initOtel()` sets up traces + metrics via OTLP gRPC; the library emits `producer.append_retry_total`, `consumer.dispatch.duration_ms`, `pending_seals_depth`, `lease_renewal_error_total`, and more.
7. **On S3, add an `AbortIncompleteMultipartUpload` lifecycle rule** to the bucket (for example, after 1 day). The compactor writes rewritten archives as multipart uploads; one a crash interrupts leaves its uploaded parts, which S3 stores and bills until they are aborted.

## License

Copyright (c) 2026 MakerX Pty Ltd.

UNLICENSED — closed-source, all rights reserved. Distributed via public npm for convenience; see [LICENSE](./LICENSE). Licensing enquiries: `hello@makerx.com.au`.
