# Messages in depth

Code on this page comes in TypeScript, Rust, and Python. The same page with one language only: [Python](https://docs.laserdata.com/md/python/laser-sdk/advanced/log.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/advanced/log.md), [Rust](https://docs.laserdata.com/md/rust/laser-sdk/advanced/log.md).

The full reference for topics and messages. For a short introduction, start with [Messages](/laser-sdk/log).

## Topics, partitions, and routing

A stream groups topics. A topic is a named log with no schema required by the SDK. Partitions store its messages in order. One connection reaches every stream. Address a topic with `laser.stream("telemetry").topic("metrics")`, or set a default stream and use `laser.topic("metrics")`. See [Connect](/laser-sdk/connect#default-stream).

Order holds within a partition. There is no total order across a topic's partitions. A publish picks a partition in one of three ways:

* Balanced, the default, spreads messages for throughput. Only messages in the same partition share an order.
* Key routing hashes a non-empty key to a partition. Messages with the same key keep their relative order.
* Partition routing names a partition number directly.

More partitions allow more parallel consumers. Fewer partitions keep more messages in one ordered sequence. Use a host, agent, or session key when those messages need a shared order.

Payloads are bytes. The raw publish adds no encoding. JSON, CBOR, MessagePack, BSON, and Avro helpers encode values into those bytes. TypeScript snippets on this page turn text into bytes with `new TextEncoder().encode(text)`.

## Replication factor

A topic's replication factor is the number of nodes that store each of its partitions. You set it when you create the topic, and it never changes. Without one, the server's default applies, which is every node of the cluster unless an operator set a number.

**TypeScript**

```ts
const metrics = laser.stream("telemetry").topic("metrics")
await metrics.ensure(6, 3)
```

**Rust**

```rust
let metrics = laser.stream("telemetry").topic("metrics");
metrics.ensure(6, Some(3)).await?;
```

**Python**

```python
metrics = laser.stream("telemetry").topic("metrics")
await metrics.ensure(6, replication_factor=3)
```

A producer that creates its topic takes the factor too: Rust `replication_factor(n)`, Python `replication_factor=`, TypeScript `replicationFactor`. All three SDKs refuse a factor outside 1 to 32 before they send anything, with an invalid error that reads `replication factor must be 1..=32`. The server also refuses a factor above the cluster's node count with `InvalidReplicationFactor` (2018), and a factor that is not a number with `InvalidOptionValue` (4042).

A write commits once a quorum of the partition's members has it: 2 of 3, 3 of 5, and never more than 3.

| Factor | Write quorum | Members that can be down while writes continue |
| --- | --- | --- |
| 1 | 1 | None, and there is no second copy |
| 2 | 2 | None, writes stop while either member is down |
| 3 | 2 | 1 |
| 5 | 3 | 2 |

* The server picks the members when it creates the topic, and they never move. Nodes added later do not take over existing partitions.
* Every node keeps the metadata of every stream and topic. On a cluster wider than the factor, a node stores only the partitions it is a member of.
* A node that does not store a partition answers reads, filtered reads, acknowledgements, and waits for it with the standard not-primary reply. The SDK readers then retry on the partition primary, which is always a member, so no reader gets an empty page from a node that does not store the partition.
* Deleting a topic waits while one of its partitions lacks a quorum of its members.
* The server's topic details list each partition's `members` and `in_sync_members`, the ids of the nodes that store it and of those caught up with its primary.

The default suits most topics. On a cluster wider than you need, a lower factor saves disk and replication traffic: 3 keeps writing through one node failure and 5 through two. A factor of 1 keeps one copy: the partition stops while its node is down and is lost with that node's disk, so keep it for data you can rebuild.

## Inspect streams and topics

The client reads what the server reports about streams, topics, partitions, and consumer groups. These calls use native Apache Iggy commands, so they work on plain Apache Iggy, Laser Stack, and LaserData Cloud. The example lists the streams, then reads the `host-cpu` topic of the `metrics` stream.

**TypeScript**

```ts
for (const stream of await laser.streams()) {
  console.log(stream.name, stream.topicsCount, stream.messagesCount)
}

const cpu = laser.stream("metrics").topic("host-cpu")
const topic = await cpu.get()
if (topic === undefined) {
  console.log("host-cpu does not exist")
} else {
  console.log(topic.partitionsCount, topic.messageExpiryMs, topic.sizeBytes)
  for (const partition of await cpu.partitions()) {
    console.log(partition.id, partition.currentOffset, partition.messagesCount)
  }
  for (const group of await cpu.consumerGroups()) {
    console.log(group.name, group.membersCount)
  }
}
```

**Rust**

```rust
for stream in laser.streams().await? {
    println!("{} {} {}", stream.name, stream.topics_count, stream.messages_count);
}

let cpu = laser.stream("metrics").topic("host-cpu");
match cpu.get().await? {
    None => println!("host-cpu does not exist"),
    Some(topic) => {
        println!("{} {:?} {}", topic.partitions_count, topic.message_expiry, topic.size_bytes);
        for partition in cpu.partitions().await? {
            println!("{} {} {}", partition.id, partition.current_offset, partition.messages_count);
        }
        for group in cpu.consumer_groups().await? {
            println!("{} {}", group.name, group.members_count);
        }
    }
}
```

**Python**

```python
for stream in await laser.streams():
    print(stream.name, stream.topics_count, stream.messages_count)

cpu = laser.stream("metrics").topic("host-cpu")
topic = await cpu.get()
if topic is None:
    print("host-cpu does not exist")
else:
    print(topic.partitions_count, topic.message_expiry_ms, topic.size_bytes)
    for partition in await cpu.partitions():
        print(partition.id, partition.current_offset, partition.messages_count)
    for group in await cpu.consumer_groups():
        print(group.name, group.members_count)
```

| Call | What it does |
| --- | --- |
| `laser.streams()` | List every stream that the connected user can read, as `StreamInfo` values |
| `stream(name).get()` | Read the stream as a `StreamInfo`, or no value when the stream does not exist |
| `stream(name).exists()` | Return whether the stream exists |
| `stream(name).topics()` | List the topics of the stream, as `TopicInfo` values |
| `stream(name).rename(new_name)` | Rename the stream. After the rename, address the stream by its new name |
| `topic.get()` | Read the topic as a `TopicInfo`, or no value when the topic or its stream does not exist |
| `topic.exists()` | Return whether the topic exists |
| `topic.partitions()` | List the partitions of the topic, as `PartitionInfo` values |
| `topic.consumer_groups()` | List the consumer groups of the topic, as `ConsumerGroupSummary` values |
| `topic.add_partitions(n)` | Add `n` partitions after the existing ones |
| `topic.delete_partitions(n)` | Delete the last `n` partitions with their messages |
| `topic.update(options)` | Change the name, the message expiry, or the size cap of the topic, with `UpdateTopicOptions`. A field you leave unset keeps its value |
| `topic.delete_segments(partition_id, count)` | Delete the oldest `count` segments of one partition with their messages. The open segment stays |
| `topic.delete()` | Delete the topic with every message in it. Returns false when the topic or its stream did not exist |
| `topic.consumer_group(name).delete()` | Delete the consumer group with its stored offsets. Returns false when the group, its topic, or its stream did not exist |

Python uses the same names. TypeScript uses `consumerGroups()`, `addPartitions(n)`, `deletePartitions(n)`, `deleteSegments(partitionId, count)`, and `consumerGroup(name).delete()`. A missing stream or topic gives no value from `get()`: `None` in Rust and Python, and `undefined` in TypeScript. `topics()`, `partitions()`, and `consumer_groups()` fail with the stream-or-topic-not-found error when the stream or topic does not exist. Test for that error with Rust `is_stream_or_topic_not_found()`, TypeScript `isStreamOrTopicNotFound(error)`, or the Python `stream_or_topic_not_found` attribute. The server refuses `add_partitions` and `delete_partitions` on a topic created with a fixed partition layout.

`UpdateTopicOptions` holds the changes that `topic.update` applies:

| Rust field | Python keyword | TypeScript option | What it changes |
| --- | --- | --- | --- |
| `name` | `name=` | `name` | The topic name |
| `expire_after` | `expire_after_ms=` | `expireAfterMs` | Keep each message for this time. Rust takes a `Duration`, and Python and TypeScript take milliseconds |
| `never_expire` | `never_expire=` | `neverExpire` | Keep messages until the size cap removes them |
| `max_topic_bytes` | `max_topic_bytes=` | `maxTopicBytes` | Cap the stored size of the topic in bytes. TypeScript takes a `bigint` |
| `unlimited_topic_size` | `unlimited_topic_size=` | `unlimitedTopicSize` | Remove the size cap |

Python takes the fields as keyword arguments, `topic.update(expire_after_ms=86_400_000)`. TypeScript takes an options object, `topic.update({ expireAfterMs: 86_400_000 })`. Set `expire_after` or `never_expire`, not both. Set `max_topic_bytes` or `unlimited_topic_size`, not both. A call that sets both fields of a pair fails with an invalid-argument error before the client sends anything. After a rename, address the topic by its new name.

| Type | Fields |
| --- | --- |
| `StreamInfo` | `id`, `name`, `topics_count`, `size_bytes`, `messages_count`, `created_at_micros` |
| `TopicInfo` | `id`, `name`, `partitions_count`, `replication_factor`, `message_expiry`, `max_size_bytes`, `size_bytes`, `messages_count`, `created_at_micros` |
| `PartitionInfo` | `id`, `segments_count`, `current_offset`, `size_bytes`, `messages_count`, `created_at_micros` |
| `ConsumerGroupSummary` | `id`, `name`, `partitions_count`, `members_count` |

* `id` is the native numeric ID that the server gave the resource. `created_at_micros` is the creation time in microseconds since the Unix epoch.
* `replication_factor` has no value when the server reports no factor. `message_expiry` has no value when messages never expire or when the topic uses the server's default expiry. `max_size_bytes` has no value when the topic has no size cap.
* Rust gives `message_expiry` as a `Duration`. Python names it `message_expiry_ms` and TypeScript names it `messageExpiryMs`, both in milliseconds.
* `current_offset` is the offset of the newest message in the partition, and 0 for an empty partition.
* TypeScript uses camelCase field names. Sizes, message counts, offsets, and creation times are `bigint` values. IDs and the other counts are `number` values.

## Typed handles and readers

`topic.json(..)` returns a typed handle. Its `publish` encodes a value and its `records(name)` reader decodes each message back. `topic.cbor(..)` does the same in CBOR. Rust takes a type parameter, `topic.json::<Reading>()`. Python takes a class, `topic.json(Reading)`. TypeScript takes a codec, `topic.json(new Json<Reading>(decode))`, whose decode function checks each value because types do not exist at runtime. `Cbor`, `Msgpack`, and `Bson` take the same decode function.

A Python typed `publish(body)` returns the publish builder, so finish with `.send()`. A Rust typed `publish(&value)` also returns a builder. A TypeScript typed `publish(value)` sends at once and takes `{ key }`, `{ partition }`, or `{ headers }` as a second argument.

A typed reader is a cursor that you own. It is not consumer group delivery, and the server does not store its offsets. It starts at offset 0 unless you restore saved offsets:

| | Rust | Python | TypeScript |
| --- | --- | --- | --- |
| Read one record | `reader.next().await` | `await reader.next()` | `await reader.next()` |
| At the current tail | `None` | `None` | `undefined` |
| Read a batch | `reader.poll().await` | `await reader.poll()` | `await reader.poll()` |
| Save offsets | `reader.offsets()`, a list with one entry per partition | `reader.offsets`, a list with one entry per partition | `reader.offsets`, a map from partition to `bigint` |
| Resume | `records(name)?.from_offsets(saved)` | `records(name, from_offsets=saved)` | `(await records(name)).fromOffsets(saved)` |
| Records per request and partition | 1000 | 1000 | 1000 |
| Record position | `MessageId` | `MessageId` with `partition_id` and `offset` | `{ partitionId, offset }` |

Change the request size with `batch(n)` in Rust and TypeScript and `records(name, batch=n)` in Python. One poll drains each partition to its tail, up to 10,000 records per partition, and returns the records in log timestamp order. The offsets are empty until the first poll or until you restore saved ones. Restoring replaces the offsets, it does not merge them.

A record that does not decode fails with a decode error that names its log position, and the next read moves past it. Rust `next()` returns the error, TypeScript `next()` returns a result with `kind: "error"`, and Python `next()` raises `TypedDecodeError`. `poll()` returns it inline next to the good records in all three. A Python `async for` loop ends on the error, so loop over `next()` to skip it. Rust and TypeScript `stream()` and Python `async for` end once the reader is caught up. `topic.replay()` is the raw cursor with the same offset rules, across every partition.

## Producing at volume

`publish()` builds one message, sends it, and waits for the result. It uses the connection's publish timeout and retries. See [Connect](/laser-sdk/connect#publish-timeouts-and-retries). For more throughput, pick a write path:

* `publish_batch()` collects messages on the client and sends them in one request. You decide when the batch goes out.
* `topic.producer()` creates a long-lived producer that sends each batch directly and retries failures. Use it as the default production path.
* A producer in background mode queues sends and writes them from a worker. It gives the most throughput. See [Background producers](#background-producers).
* `topic.batching()` returns a client-side accumulator that flushes on a record count, a byte size, or a timer. See [Batching producers](#batching-producers).

### Direct producer

The Rust producer builder takes these options. Python takes the same values as keyword arguments, and TypeScript takes them as options.

| Option | Default | What it does |
| --- | --- | --- |
| `batch_length(n)` | 1000 | Most messages in one server request. A larger `send_batch` is split into requests of this size, sent one after another |
| `linger(d)` | 0 | Minimum gap between sends. A send waits out what is left of it since the previous one. Direct mode only |
| `retries(n, interval)` | The connection's publish retries, 3 retries with a first delay of 250 ms | Resend attempts after a failure |
| `retry_backoff(d)` | The connection's first retry delay | Changes the delay and keeps the retry count |
| `routing(r)` | `Balanced` | Default routing for every send: `Routing::Balanced`, `Routing::key(k)`, or `Routing::Partition(n)` |
| `create_stream(bool)` | `false` | Create a missing stream on init. Streams are usually provisioned ahead of time, and a scoped identity may not create one |
| `create_topic(bool)` | `true` | Create a missing topic on init. Turn off to fail fast on a wrong name |
| `partitions(n)` | 1 | Partition count when the producer creates the topic |
| `replication_factor(n)` | Server default | Nodes that store each partition when the producer creates the topic, from 1 to 32. See [Replication factor](#replication-factor) |
| `expire_after(d)` / `never_expire()` | Server default | Message retention when the producer creates the topic. Setting both forms, or a zero value, fails with an invalid error before any network call |
| `max_topic_bytes(n)` / `unlimited_topic_size()` | Server default | Size limit when the producer creates the topic. Setting both forms, or a zero value, fails with an invalid error before any network call |
| `background(config)` | Direct mode | Switch to Apache Iggy's buffered mode. `batch_length` and `linger` are then ignored |
| `sharding(picker)` | The sharding of `background` | Pick the background shard of each send with your own function. Needs `background`. See [Pick the shard of each send](#pick-the-shard-of-each-send) |
| `encryption(e)` | None | Encrypt the payload and the headers of each record on the client. See [Client-side encryption](#client-side-encryption) |

Python's `topic.producer(..)` takes `batch_length`, `linger_ms`, `retries`, `retry_interval_ms`, `key` or `partition` for the default routing, `create_stream`, `create_topic`, `partitions`, `replication_factor`, `expire_after_ms` or `never_expire`, `max_topic_bytes` or `unlimited_topic_size`, `background`, `sharding`, and `encryption`. `linger_ms` and `expire_after_ms` take a float, so a fraction of a millisecond is kept. `max_topic_bytes` is a positive byte count. `send` and `send_batch` initialize the producer on first use. Call `await producer.init()` when startup must fail before the service accepts work. `send_batch` takes raw payloads or `(payload, headers)` pairs.

TypeScript's `topic.producer(options)` takes `routing`, `retries`, `retryBackoffMs`, `createStream`, `createTopic`, `partitions`, `replicationFactor`, `expireAfterMs` or `neverExpire`, `batchLength`, `lingerMs`, `maxTopicBytes` or `unlimitedTopicSize`, `background`, `sharding`, and `encryption`. `expireAfterMs` is a number of milliseconds and `maxTopicBytes` is a `bigint`. The producer needs no init call. It creates a missing topic before the first send unless you turn that off. It creates a missing stream only when `createStream` is set. A transport that cannot set topic expiry, size limits, or a replication factor refuses those options.

This sample follows the [`native-streaming`](https://github.com/laserdata/laser-sdk/tree/main/examples/rust/src/native-streaming) example:

**TypeScript**

```ts
import { HeaderValue } from "@laserdata/laser-sdk"

const text = new TextEncoder()
await using producer = topic.producer({
  batchLength: 1_000,
  lingerMs: 5,
  retries: 3,
  retryBackoffMs: 1_000
})

await producer.send(text.encode("reading-0"), {
  key: text.encode("node-7"),
  headers: { type: HeaderValue.uint16(7) }
})

const payloads = [text.encode("reading-1"), text.encode("reading-2")]
await producer.sendBatch(payloads)
```

**Rust**

```rust
use laser_sdk::prelude::*;
use laser_sdk::stream::{HeaderKey, HeaderValue};
use std::time::Duration;

let producer = topic
    .producer()
    .batch_length(1_000)
    .linger(Duration::from_millis(5))
    .retries(Some(3), Some(Duration::from_secs(1)))
    .routing(Routing::Balanced)
    .build()
    .await?;

producer
    .send_keyed(
        ProducerMessage::new(b"reading-0".as_slice())
            .header(HeaderKey::try_from("type")?, HeaderValue::from(7_u16)),
        b"node-7".to_vec(),
    )
    .await?;

let batch = vec![
    ProducerMessage::new(b"reading-1".as_slice()),
    ProducerMessage::new(b"reading-2".as_slice()),
];
producer.send_batch(batch).await?;
```

**Python**

```python
producer = topic.producer(
    batch_length=1000,
    linger_ms=5,
    retries=3,
    retry_interval_ms=1000,
)
await producer.init()

await producer.send(
    b"reading-0",
    headers={"type": ("uint16", 7)},
    key=b"node-7",
)

values = [b"reading-1", b"reading-2"]
await producer.send_batch(values)
```

A send can override the producer's routing. Rust uses `send_keyed(msg, key)` or `send_to_partition(msg, n)`. Python's `send` takes `key=` or `partition=`. TypeScript's `send` takes `{ key }` or `{ partition }`. Do not pass a key and a partition together. Batches take the same override through Rust `send_batch_with_routing`, Python `send_batch(key=, partition=)`, and TypeScript `sendBatch(messages, { key })`. All records in one batch share the key or partition.

Producers use the connection's publish retry count and delay unless you set them. In direct mode, retry delays start at the configured delay, 250 ms by default, double after each failure, and stop at 30 seconds. Only temporary errors are retried. In background mode the first resend goes at once, and later resends wait the configured delay each time without doubling. Background mode resends after any error except a lost confirmation, which means the batch may have been written. Each producer setup attempt also uses the publish timeout and retry budget. A producer that loses a race to create the same stream or topic treats it as success and reads the winner's resource. These are the producer-level overrides:

| Goal | Rust | Python | TypeScript |
| --- | --- | --- | --- |
| Inherit the connection values | Leave `retries` unset | `retries=None` and `retry_interval_ms=None`, the defaults | Leave `retries` and `retryBackoffMs` unset |
| Disable resends | `retries(Some(0), None)` | `retries=0` | `retries: 0` |
| Change only the delay | `retry_backoff(d)` | `retry_interval_ms=` with `retries=None` | `retryBackoffMs` without `retries` |

In Rust direct mode, `retries(None, ..)` also means no retries.

Creation settings apply only to topics that do not exist yet. A producer never changes an existing topic's expiry, size limit, or replication factor. A topic created by `topic.ensure(..)` never expires, and `ensure` leaves an existing topic as it is. Two producers that create the same topic at once both succeed in all three SDKs, because the one that loses the race accepts the existing topic.

### Background producers

Background mode queues each send and writes it from a worker. A send returns once the queue accepts the records, so it carries no commit confirmation, and the publish timeout does not cover that step. Drain the queue before you exit, or the queued records are lost.

All three SDKs take the same settings, with Apache Iggy's background defaults: one ordered shard, a flush at 1000 sends, 1 MiB, or the linger time, a 32 MiB buffer budget, and the `block` failure mode. Ordered sharding, the default, keeps every send of the producer on one shard in send order. Balanced sharding spreads sends over every shard and gives up that order.

| Setting | Rust `BackgroundConfig::builder()` | Python `BackgroundConfig(..)` | TypeScript `background: { .. }` |
| --- | --- | --- | --- |
| Shards | `num_shards(n)` | `num_shards=` | `shards` |
| Sharding | `sharding(Box::new(BalancedSharding::default()))` | `sharding="balanced"` | `sharding: "balanced"` |
| Flush at sends | `batch_length(n)` | `batch_length=` | `batchLength` |
| Flush at bytes | `batch_size(n)` | `batch_size=` | `batchBytes` |
| Linger | `linger_time(d)` | `linger_ms=` | `lingerMs` |
| Buffer budget | `max_buffer_size(n)` | `max_buffer_size=` | `maxBufferBytes` |
| Writes in flight | `max_in_flight(n)` | `max_in_flight=` | `maxInFlight` |
| Full buffer | `failure_mode(..)` | `failure_mode=` and `block_timeout_ms=` | `failureMode` |
| Failed write | `error_callback(..)` | `error_callback=` | `onError` |

Python selects the mode with `background=True` for the defaults or `background=BackgroundConfig(..)` to change them. Rust's builder takes Apache Iggy types: `linger_time` takes an `IggyDuration` (convert a `Duration` with `.into()`), `max_buffer_size` takes an `IggyByteSize`, `failure_mode` takes a `BackpressureMode` from `laser_sdk::iggy::clients::producer_config`, and `error_callback` takes an `ErrorCallback` from `laser_sdk::iggy::clients::producer_error_callback`. Python's `linger_ms` takes a float, so a fraction of a millisecond is kept.

`flush()` waits for sends in flight and writes every queued record, and the producer keeps accepting sends. Close a background producer with `shutdown()`. It flushes the same way and then closes. Both act for every clone of the producer. After shutdown, a send fails with an invalid-argument error (`InvalidError` in Python and TypeScript). A second `shutdown()` returns once the first one finishes.

Without an error callback, the producer keeps each failed background write, and the next `flush()` or `shutdown()` fails with one publish failure that lists the records of every failed write. Set the error callback to handle failures as they happen instead. Rust's callback receives Apache Iggy's `ErrorCtx` with the cause, the stream and topic, the confirmed ranges, and the messages. A Python `error_callback` receives a `PublishFailedError` with `stream`, `topic`, `committed`, `unconfirmed`, and the cause as `__cause__`. It can be a plain or async callable. TypeScript hands each failure to `onError` and awaits a returned promise, and a failure whose `onError` throws is kept as well.

**TypeScript**

```ts
const text = new TextEncoder()
const producer = topic.producer({
  background: {
    shards: 2,
    lingerMs: 5,
    onError: (error) => console.error(error.publishCause())
  }
})

await producer.send(text.encode("reading-0"))
await producer.send(text.encode("reading-1"))
await producer.shutdown()
```

**Rust**

```rust
use laser_sdk::stream::BackgroundConfig;
use std::time::Duration;

let producer = topic
    .producer()
    .background(
        BackgroundConfig::builder()
            .num_shards(2)
            .linger_time(Duration::from_millis(5).into())
            .build(),
    )
    .build()
    .await?;

producer.send(b"reading-0".as_slice()).await?;
producer.send(b"reading-1".as_slice()).await?;
producer.shutdown().await?;
```

**Python**

```python
import laser_sdk as ls

def report(error: ls.PublishFailedError) -> None:
    print(f"{len(error.unconfirmed)} record(s) unconfirmed: {error.__cause__}")

producer = topic.producer(
    background=ls.BackgroundConfig(num_shards=2, linger_ms=5, error_callback=report)
)
await producer.init()

await producer.send(b"reading-0")
await producer.send(b"reading-1")
await producer.shutdown()
```

### Pick the shard of each send

A background producer can pick the shard of each send with your own function. Pass it as the `sharding` option: Rust `sharding(picker)`, Python `topic.producer(sharding=)`, TypeScript `sharding` in the producer options. The function replaces the named sharding of the background configuration.

The function gets a `ShardRequest` and returns a shard index. A `ShardRequest` holds the shard count (`shards`, at least one), the `stream`, the `topic`, and the number of records in the send (`records`). The example puts sends of 100 records or more on the last shard and every other send on shard 0.

**TypeScript**

```ts
import type { ShardRequest } from "@laserdata/laser-sdk"

const producer = topic.producer({
  background: { shards: 2 },
  sharding: (request: ShardRequest) => (request.records >= 100 ? request.shards - 1 : 0)
})
```

**Rust**

```rust
use laser_sdk::stream::{BackgroundConfig, ShardRequest};

let producer = topic
    .producer()
    .background(BackgroundConfig::builder().num_shards(2).build())
    .sharding(|request: &ShardRequest<'_>| {
        Ok(if request.records >= 100 { request.shards - 1 } else { 0 })
    })
    .build()
    .await?;
```

**Python**

```python
import laser_sdk as ls

def pick_shard(request: ls.ShardRequest) -> int:
    return request.shards - 1 if request.records >= 100 else 0

producer = topic.producer(
    background=ls.BackgroundConfig(num_shards=2),
    sharding=pick_shard,
)
```

* The `sharding` option needs background mode. A producer that has `sharding` without `background` fails to build with an invalid-argument error.
* An index that is not below the shard count fails the send with an invalid-argument error. An error from the function also fails the send. A Rust function returns `Result<usize, LaserError>`, a Python function can raise, and a TypeScript function can throw.
* When the send fails in one of these ways, the producer queues no record of it.

### Batching producers

`topic.batching()` returns a producer that queues records on the client and sends each flush as one append. A flush runs when the queue reaches `max_records`, when the queued payload reaches `max_bytes`, or when `linger` expires, whichever comes first. A linger below 1 ms is raised to 1 ms. With a `partition_key`, every record of the handle goes to that key. Without one, each flushed batch is balanced across partitions. Rust needs the `agent` feature, because the linger timer runs on tokio.

| Setting | Default | Rust | Python | TypeScript |
| --- | --- | --- | --- | --- |
| Record limit | 512 | `max_records(n)` | `max_records=` | `maxRecords(n)` |
| Byte limit | 1 MiB | `max_bytes(n)` | `max_bytes=` | `maxBytes(n)` |
| Linger | 5 ms | `linger(Duration)` | `linger_ms=` | `linger(ms)` |
| Partition key | None | `partition_key(key)` | `partition_key=` | `partitionKey(key)` |

`send()` queues one payload with headers. Rust always takes a headers map, which can be empty. Python and TypeScript make headers optional. It flushes inline when a size limit trips, so backpressure lands on the sender. `flush()` sends what is queued, and `close()` flushes and stops the timer. Flushes run one at a time, so batches reach the log in queue order. After `close()`, a send raises `InvalidError` in Python and TypeScript. Rust's `close()` takes the producer by value. TypeScript `await using` and Python `async with` close the producer at the end of their scope.

A failed timer flush never stops the timer. Its failure is kept until the next `send()`, `flush()`, or `close()` reports it. A `send()` that finds a kept failure does not queue its own record. It returns the kept failure with that record added to the unconfirmed records. `flush()` and `close()` report the kept failure after they drain the queue. When several flushes fail before you ask, you get one publish failure that lists the records of every failed batch.

**TypeScript**

```ts
await using batching = topic
  .batching()
  .maxRecords(512)
  .maxBytes(1_048_576)
  .linger(5)
  .partitionKey("node-7")
  .build()

const text = new TextEncoder()
await batching.send(text.encode("reading-0"))
await batching.send(text.encode("reading-1"))
await batching.flush()
```

**Rust**

```rust
use laser_sdk::stream::Headers;
use std::time::Duration;

let batching = topic
    .batching()?
    .max_records(512)
    .max_bytes(1_048_576)
    .linger(Duration::from_millis(5))
    .partition_key("node-7")
    .build();

batching.send(b"reading-0".to_vec(), Headers::new()).await?;
batching.send(b"reading-1".to_vec(), Headers::new()).await?;
batching.flush().await?;
batching.close().await?;
```

**Python**

```python
batching = topic.batching(
    max_records=512,
    max_bytes=1_048_576,
    linger_ms=5,
    partition_key="node-7",
)

await batching.send(b"reading-0")
await batching.send(b"reading-1")
await batching.flush()
await batching.close()
```

### When a publish fails

A publish that gives up reports what it left behind. `committed` lists the ranges the server confirmed, each with the stream and topic IDs, the partition, and the base offset. `unconfirmed` holds the records without a confirmation. Do not publish the confirmed ranges again. An unconfirmed record can already exist on the server if its acknowledgement was lost. Unconfirmed records keep the message IDs that the attempts used.

A direct producer splits a large batch into requests of `batch_length` records. A failure reports the confirmed requests and every record from the failed request on. Inspect the report before you retry.

| | Rust | Python | TypeScript |
| --- | --- | --- | --- |
| Failure | `LaserError::PublishFailed` | `PublishFailedError` | `PublishFailedError` |
| Confirmed ranges | `committed` | `committed` | `committed` |
| Unconfirmed records | `unconfirmed`, a list of `IggyMessage` | `unconfirmed`, a list of `IggyMessage` | `unconfirmed` |
| Target | `stream` and `topic` | `stream` and `topic` | `stream` and `topic` |
| Original error | `publish_cause()` | `__cause__` | `publishCause()`, or the free `publishCause(error)` |
| Retryable | `is_retryable()` | `retryable` | `isRetryable(error)` |

The retryable check answers for the original error. To resend the unconfirmed records with their original message IDs, pass them back to `topic.batch(..)`. A server that deduplicates by message ID then drops any record that already landed. The records carry no routing, so the resend does not keep the original key or partition.

**TypeScript**

```ts
import { PublishFailedError } from "@laserdata/laser-sdk"

try {
  await producer.sendBatch(payloads)
} catch (error) {
  if (!(error instanceof PublishFailedError)) throw error
  console.error(
    `${error.committed.length} range(s) confirmed, ${error.unconfirmed.length} record(s) unconfirmed`,
    error.publishCause()
  )
  await topic.batch(error.unconfirmed)
}
```

**Rust**

```rust
use laser_sdk::prelude::LaserError;

if let Err(error) = producer.send_batch(batch).await {
    eprintln!("cause: {}", error.publish_cause());
    if let LaserError::PublishFailed(failure) = error {
        eprintln!(
            "{} range(s) confirmed, {} record(s) unconfirmed",
            failure.committed.len(),
            failure.unconfirmed.len()
        );
        topic.batch(failure.unconfirmed, None).await?;
    }
}
```

**Python**

```python
import laser_sdk as ls

try:
    await producer.send_batch(values)
except ls.PublishFailedError as error:
    print(
        f"{len(error.committed)} range(s) confirmed, "
        f"{len(error.unconfirmed)} record(s) unconfirmed",
        error.__cause__,
    )
    await topic.batch(error.unconfirmed)
```

## Consumers, offsets, and commit policies

`topic.consumer(name, partition)` builds a named reader for one partition. `topic.consumer_group(group)` returns a group handle, and `group.consumer()` builds a reader that joins the group. The server gives each partition to one member and rebalances as members join and leave. In Python, `partition` is a keyword that defaults to 0. In TypeScript, `topic.consumer(name, partitionId, options)` builds the named reader and `await topic.consumerGroup(group).consumer(options)` builds the group reader.

Every consumed message carries its log position in `position`, a partition and an offset. Read the offset as `message.position.offset`. The message also keeps the exact Iggy headers, the message ID, the checksum, and the timestamps. A malformed header block in TypeScript marks the record instead of failing the whole poll.

Delivery is at least once. A crash between delivery and commit delivers the message again, so handlers must be safe to repeat.

### Two group paths

A group consumer reads one of two ways. On a server that resolves consumer group policies, such as Laser Stack and LaserData Cloud, it reads through the group and acknowledges with fenced group commits. This page calls that the group-policy path. On plain Apache Iggy it is the native Iggy group consumer, called the native path here. Both paths join the group when the consumer is built. The group-policy path is also how [Filters](/laser-sdk/consumer-filters) run.

`create_group` defaults to true (Python `create_group=`, TypeScript `createGroup`). The server stores offsets by consumer name or group. Reconnect with the same name to resume from the stored offset.

### How a read waits

A consumer never sleeps between polls. Each poll asks the server to hold the read until `min_count` new records are there or `max_wait` passes, and the server then answers with what it has. An idle consumer sends one request per wait, and a new record arrives without a polling delay.

| Setting | Default | Rust | Python | TypeScript |
| --- | --- | --- | --- | --- |
| Server wait, 0 to 600 seconds. Zero answers at once | 5 seconds | `max_wait(Duration)` | `max_wait_ms=` | `maxWaitMs` |
| New records that end the wait, from 1 to `batch_length` | 1 | `min_count(n)` | `min_count=` | `minCount` |
| Record bytes in one reply | 1 MiB | `max_bytes(n)` | `max_bytes=` | `maxBytes` |

A record larger than `max_bytes` comes alone, so a poll always makes progress. A value out of range is refused before the consumer polls. `min_count` and `max_bytes` shape native reads. A group-policy consumer reads pages of at most `batch_length` records and, when a whole round is idle, asks the server for a filtered wait of up to `max_wait`. As soon as one node answers, it cancels its waits on the other nodes, and a cancelled wait answers empty at once. See [Waiting for new records](/laser-sdk/advanced/consumer-filters#waiting-for-new-records).

### Where a consumer starts

`start_at(..)` picks the first position when no stored offset exists. The default is `Next`.

* Rust takes `ConsumerStart::First`, `Last`, `Next`, `Offset(n)`, or `TimestampMicros(t)`.
* TypeScript takes `startAt` with `{ kind: "first" | "last" | "next" }`, or `{ kind: "offset" | "timestampMicros", value }` where `value` is a `bigint`.
* Python takes `polling="first" | "last" | "next"`, or `offset=` or `timestamp_micros=`.

`allow_replay()` in Rust, `allow_replay=True` in Python, and `allowReplay: true` in TypeScript permit reads at or below a stored offset. Use it to replay a group from `First`. Without it, a native consumer skips records it already consumed. A group-policy consumer honors its start position as given.

`Next` does not skip the first record of a fresh consumer. With no stored offset, it starts at the first retained record. With a stored offset of 0, it starts at offset 1. Storing offset 0 acknowledges that record. It is not an empty starting state.

### Commit and offset control

`commit(message)` acknowledges a processed record. A native commit stores the offset under the partition history that delivered the record: a record read before its topic was recreated, its partition moved to another member, or a seek of its partition stores nothing, and a record from another consumer is refused. Native consumers also expose `store_offset(offset, partition)` and `delete_offset(partition)` for direct offset control (TypeScript `storeOffset(offset, partitionId?)` and `deleteOffset(partitionId?)`, Python `store_offset(offset, partition=)` and `delete_offset(partition=)`). Group-policy consumers refuse those two calls, because their acknowledgments must pass the group and policy checks.

`last_consumed_offset(p)` and `last_stored_offset(p)` read local progress (TypeScript `lastConsumedOffset(p)` and `lastStoredOffset(p)`, awaited in Python). They are diagnostics, not a resume point. On the native path in Rust and Python, the Iggy cache can hold an initial zero before any commit. On the group-policy path, `last_stored_offset` reports the last acknowledged offset. Resume with the `Next` start instead of computing a position from them. `stored_offset(p)` (TypeScript `storedOffset(p)`) reads the stored offset and the partition's current offset from the server, or returns nothing when the server stores none yet. TypeScript refuses it on an unnamed partition consumer.

`seek(partition, start)` on a native consumer reads a partition again from an earlier record, or past a later one. The rest of the partition's polled batch is dropped and a record delivered before the seek commits nothing. Under the polling policies a seek to an offset above zero first stores the offset before it, so a restart resumes there. Group-policy consumers refuse it, like `store_offset`.

**TypeScript**

```ts
await consumer.seek(0, { kind: "offset", value: 1n })
const again = await consumer.nextWithin(10_000)
```

**Rust**

```rust
consumer.seek(0, ConsumerStart::Offset(1)).await?;
let again = consumer.next_within(Duration::from_secs(10)).await?;
```

**Python**

```python
await consumer.seek(0, offset=1)
again = await consumer.next_within(10_000)
```

A deleted and recreated stream or topic is a new history that starts at offset 0. Group-policy consumers detect it, reset partition progress, and report `source_changed` before the next read resumes. A group handle built from a numeric ID refuses a recreated stream or topic and needs a new reader.

### Commit policies

The commit policy decides when the consumer stores offsets on the server:

| Policy | Stores the offset |
| --- | --- |
| `All` (default) | Once the last record of a poll is handled, and the handled prefix at shutdown |
| `Polling` | Native consumers: the end of the polled batch, before delivery. Group-policy consumers: the handled prefix at the next poll or shutdown |
| `Each` | After every yielded record |
| `Every(n)` | After every `n` yielded records |
| `Interval(d)` | On a timer |
| `IntervalOrPolling(d)` / `IntervalOrAll(d)` / `IntervalOrEach(d)` / `IntervalOrEvery(d, n)` | The interval or the event, whichever comes first |
| `Disabled` | Never. You call `commit(message)` yourself |

A record counts as handled once your code asks for the next one or shuts the consumer down, so under the default `All` a crash delivers the rest of the current poll again on every server. `Polling` can skip unprocessed records after a crash on the native path, because it commits before delivery. Group-policy consumers acknowledge the delivered prefix when consumption continues or shuts down. Use `Disabled` and commit after successful processing when only finished work may advance. Native consumers send an offset store, and group-policy consumers send a fenced acknowledgment.

**TypeScript**

```ts
await using consumer = await topic.consumerGroup("workers").consumer({
  batchLength: 100,
  commitPolicy: { kind: "disabled" },
  startAt: { kind: "first" },
  allowReplay: true,
  maxWaitMs: 1_000,
  minCount: 10
})

for await (const message of consumer) {
  handle(message)
  await consumer.commit(message)
}
```

**Rust**

```rust
let mut consumer = topic
    .consumer_group("workers")
    .consumer()
    .batch_length(100)
    .max_wait(Duration::from_secs(1))
    .min_count(10)
    .start_at(ConsumerStart::First)
    .allow_replay()
    .commit_policy(CommitPolicy::Disabled)
    .build()
    .await?;

while let Some(message) = consumer.next().await {
    let message = message?;
    handle(&message)?;
    consumer.commit(&message).await?;
}
consumer.shutdown().await?;
```

**Python**

```python
consumer = topic.consumer_group("workers").consumer(
    batch_length=100,
    max_wait_ms=1_000,
    min_count=10,
    polling="first",
    auto_commit="disabled",
    allow_replay=True,
)
await consumer.init()

async for message in consumer:
    handle(message)
    await consumer.commit(message)

await consumer.shutdown()
```

To commit automatically instead, drop the manual commits and set a policy: `commit_policy(CommitPolicy::IntervalOrEach(Duration::from_secs(1)))` in Rust, `auto_commit="each", commit_interval_ms=1000` in Python, or `commitPolicy: { kind: "intervalOrEach", intervalMs: 1_000 }` in TypeScript. In TypeScript, `consumer.stream({ signal })` takes an `AbortSignal`. Aborting it stops the loop with a `CancelledError`.

### Waiting with a timeout

`next_within(timeout)` returns the next record, or fails when the time runs out. Rust takes a `Duration`, and Python and TypeScript take milliseconds. A timeout is a typed error: `LaserError::Timeout` in Rust and `TimeoutError` in Python and TypeScript. After shutdown, the call fails with an invalid-state error.

TypeScript keeps a poll that outlives the timeout. The next call resumes that poll and can receive its late record. A timeout never starts overlapping polls and never acknowledges a record that the caller did not receive.

**TypeScript**

```ts
import { TimeoutError } from "@laserdata/laser-sdk"

try {
  const message = await consumer.nextWithin(5_000)
  handle(message)
} catch (error) {
  if (!(error instanceof TimeoutError)) throw error
  // nothing arrived in five seconds
}
```

**Rust**

```rust
match consumer.next_within(Duration::from_secs(5)).await {
    Ok(message) => handle(&message)?,
    Err(LaserError::Timeout(_)) => {
        // nothing arrived in five seconds
    }
    Err(error) => return Err(error),
}
```

**Python**

```python
import laser_sdk as ls

try:
    message = await consumer.next_within(5_000)
    handle(message)
except ls.TimeoutError:
    pass  # nothing arrived in five seconds
```

### Differences by language

All three SDKs share these consumer defaults: `batch_length` 1000, a 5 second server wait that ends at the first new record, 1 MiB per reply, the `All` policy, the `Next` start, a 1 second wait before a failed poll is retried, and group creation and join on build. All three also set the failed-poll wait and the init retries: Rust `polling_retry_interval` and `init_retries`, Python `polling_retry_interval_ms`, `init_retries`, and `init_retry_interval_ms`, TypeScript `pollingRetryIntervalMs` and `initRetries: { retries, intervalMs }`. These parts differ:

* Rust sets one of the ten `CommitPolicy` variants with `commit_policy(..)`.
* Python picks a policy with `auto_commit`: `disabled`, `interval`, `polling`, `all` (the default), `each`, or `every`. `commit_interval_ms` defaults to 0, which keeps the plain policy. A positive value selects the interval variant, such as `IntervalOrEach`. `interval` needs a positive `commit_interval_ms`, and `every` needs `commit_every`. The consumer initializes on first read. Call `await consumer.init()` when startup must fail before the service accepts work.
* TypeScript sets `commitPolicy` with the same ten variants as `{ kind, intervalMs, count }` objects, such as `{ kind: "disabled" }` or `{ kind: "every", count: 10 }`.

`shutdown()` stops polling and leaves the group. Automatic policies store the handled prefix first. Native `Polling` commits before delivery, so its shutdown does not prove that every record was processed. If a native consumer delivered offset 0 on a partition, automatic shutdown stores offset 0 explicitly unless an earlier store already covers it. With `Disabled`, progress follows your commits.

Unnamed TypeScript consumers have isolated identities and default to no automatic commit. Use a stable name and an explicit commit policy to resume durable progress.

## Client-side encryption

Client-side encryption seals each record on the client before the record goes to the server, so the server stores only ciphertext. The SDK uses the Apache Iggy AES-256-GCM format: a random 12-byte nonce, the ciphertext, and the 16-byte tag. The Rust, Python, and TypeScript clients and the Apache Iggy encryptor read each other's records.

Make the encryption from a 32-byte key: Rust `Encryption::aes256_gcm(key)`, Python `Encryption.aes256_gcm(key)`, or TypeScript `Encryption.aes256Gcm(key)`. A key of another length fails with an invalid-argument error. Give the encryption to the producer and to each consumer with the `encryption` option.

The producer encrypts the payload and the user-header block of each record. The block holds every user header, so the `agdx.*` and `gen_ai.*` headers are sealed with the other user headers. A consumer with the same key decrypts both. A consumer without the key reads the sealed payload, and its headers do not decode. The decoded headers are empty, the malformed-headers flag is set (`headers_malformed` in Rust and Python, `headersMalformed` in TypeScript), and the sealed block stays in the raw user headers (`user_headers` or `userHeaders`). The examples read the key as 64 hex characters from the `METRICS_ENCRYPTION_KEY` environment variable. Keep the key out of source code and out of logs.

**TypeScript**

```ts
import { Encryption } from "@laserdata/laser-sdk"

const key = Buffer.from(process.env.METRICS_ENCRYPTION_KEY ?? "", "hex")
const encryption = Encryption.aes256Gcm(key)

const text = new TextEncoder()
await using producer = topic.producer({ encryption })
await producer.send(text.encode(JSON.stringify({ host: "node-7", cpu: 82 })))

await using consumer = await topic.consumerGroup("dashboards").consumer({ encryption })
const message = await consumer.nextWithin(5_000)
```

**Rust**

```rust
use laser_sdk::prelude::LaserError;
use laser_sdk::stream::Encryption;
use std::time::Duration;

let hex = std::env::var("METRICS_ENCRYPTION_KEY")
    .map_err(|_| LaserError::Invalid("METRICS_ENCRYPTION_KEY is not set".to_owned()))?;
let key = (0..hex.len())
    .step_by(2)
    .map(|at| hex.get(at..at + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()))
    .collect::<Option<Vec<u8>>>()
    .ok_or_else(|| LaserError::Invalid("METRICS_ENCRYPTION_KEY is not hex".to_owned()))?;
let encryption = Encryption::aes256_gcm(&key)?;

let producer = topic.producer().encryption(encryption.clone()).build().await?;
producer.send(br#"{"host":"node-7","cpu":82}"#.as_slice()).await?;

let mut consumer = topic
    .consumer_group("dashboards")
    .consumer()
    .encryption(encryption)
    .build()
    .await?;
let message = consumer.next_within(Duration::from_secs(5)).await?;
```

**Python**

```python
import os

import laser_sdk as ls

key = bytes.fromhex(os.environ["METRICS_ENCRYPTION_KEY"])
encryption = ls.Encryption.aes256_gcm(key)

producer = topic.producer(encryption=encryption)
await producer.send(b'{"host": "node-7", "cpu": 82}')

consumer = topic.consumer_group("dashboards").consumer(encryption=encryption)
message = await consumer.next_within(5_000)
```

| | Rust | Python | TypeScript |
| --- | --- | --- | --- |
| Make the encryption | `Encryption::aes256_gcm(key)` | `Encryption.aes256_gcm(key)` | `Encryption.aes256Gcm(key)` |
| Producer | `ProducerBuilder::encryption(e)` | `topic.producer(encryption=e)` | `encryption` in the producer options |
| Consumer | `ConsumerBuilder::encryption(e)` | `encryption=e` on `topic.consumer(..)` and `group.consumer(..)` | `encryption` in the consumer options |
| A record that does not decrypt | `LaserError::Transport` | `TransportError` | `TransportError` |

* Encryption works for partition consumers and for group consumers on both [group paths](#two-group-paths).
* A record that does not decrypt fails one read with a transport error that carries Apache Iggy error code 72. A record that is too short, a changed record, and a record sealed with another key all fail this way. The record counts as handled, and the next read continues after it.
* An encrypted consumer refuses the `Polling` and `IntervalOrPolling` commit policies with an invalid-argument error. Python spells them `auto_commit="polling"`, without and with `commit_interval_ms`, and TypeScript spells them `{ kind: "polling" }` and `{ kind: "intervalOrPolling", intervalMs }`. Under these policies the server stores the offset of a poll before the client decrypts it. Use the default `All` or another policy that stores handled records.
* A publish failure and a background error callback list the records as you sent them, before encryption.
* The server cannot read encrypted payloads or headers, so a [filter](/laser-sdk/consumer-filters) cannot evaluate them.
* `encrypt(value)` and `decrypt(value)` on the same encryption object seal and open one value outside a producer and a consumer. `decrypt` fails with error code 72 in the same cases as a consumer.

## Receive only matching records

[Filters](/laser-sdk/consumer-filters) let one shared topic deliver a different subset to each consumer group. The server selects records before they cross the network. Configure the policy through `topic.consumer_group(name).filter()`. Normal group consumers and `group.reader()` apply it, and the group's progress still covers every record the server scanned. Raw Iggy consumers ignore the filter and receive every record, so do not mix them with Laser consumers on one group.

## Apache Iggy access

Rust's `topic.iggy_producer()`, `topic.iggy_consumer(..)`, and `topic.iggy_consumer_group(group)` return native Iggy builders on the same connection, and `laser.client()` returns the client. Use them for settings that Laser SDK does not expose. TypeScript exposes the underlying client as `laser.client`. Python has no raw Iggy accessor. To list and read streams, topics, partitions, and consumer groups, use the calls in [Inspect streams and topics](#inspect-streams-and-topics), which all three SDKs have.

## Durability

Publish completion follows the topic's durability policy. A local queue that accepted a record does not prove the server stored it, and neither does a background send that returned. Message durability and consumer offset durability are independent. See [Topic durability](/deployments/server#topic-durability) and [Acknowledgements and offset commits](/deployments/server#acknowledgements-and-offset-commits).

## Producer statistics

Producers in all three SDKs can report statistics over a separate observer connection. Set the variables before you create producers. A telemetry error never fails a publish.

| Setting | Environment variable | Default | Range |
| --- | --- | --- | --- |
| Report interval | `LASER_PRODUCER_TELEMETRY_INTERVAL_MS` | `10000` | `0` disables, otherwise `1000` through `60000` |
| Reported handles per connection | `LASER_PRODUCER_TELEMETRY_MAX_PRODUCERS` | `32` | `0` through `32` |

| Counter | Meaning |
| --- | --- |
| Submitted records and bytes | Each application send once, before retries. Payload bytes only, no headers or framing |
| Confirmed records and bytes | Fully successful synchronous send calls. Unavailable for background sends |
| Failed calls | Send calls that returned an error |
| Last success | The last successful application call |
| Retries | Unavailable when the native client does not expose its attempts |
| Latency p50, p99, p99.9 | Publish-call time including retry delays, as power-of-two bucket upper bounds. p99 needs 100 calls, p99.9 needs 1000 |

* A failed batch can have committed a prefix that the confirmed counters leave out. The counters are SDK reports. Do not use them as delivery totals, exactly-once evidence, usage metering, or authorization input.
* A value outside its range is clamped to the range. A report expires after three intervals. Handles past the limit publish normally and are left out. A producer ID stays stable for the life of its handle, across reconnects.
* A Laser built from an injected client that cannot open a second authenticated connection does not report. Reports also need a server that answers the AGDX hello, so plain Apache Iggy gets none.
* The Producers tab of a topic in Stream UI shows the connected node only. The observer node can differ from the publishing node. Unknown values show as unavailable, never as zero.

## Key operations

| Operation | What it does |
| --- | --- |
| `stream(name).topic(name)` | Address a topic on any stream |
| `topic.ensure(partitions, replication_factor)` | Create the topic if it does not exist, with a fixed partition count, an optional [replication factor](#replication-factor), and no message expiry |
| `publish().payload(bytes)` | Append one raw message |
| `.json(v)` / `.msgpack(v)` | Encode the body before publish |
| `.avro(schema, schema_id, v)` | Encode a body as an Avro datum under a registered writer schema. Rust needs the `schema-codecs` feature |
| `.claim_check(store, threshold)` | Store a large body in a blob store and publish a reference (TypeScript `claimCheck`). Rust needs the `agent` feature |
| `.partition_key(key)` | Route by key for per-key order |
| `.index(key, value)` | Stamp an indexed text header, so a [view](/laser-sdk/views) can query it |
| `.header(key, value)` | Attach a text header that stays on the record and is not queryable. Use `topic.producer()` for typed headers |
| `publish_batch()` | Collect several messages into one request |
| `topic.json(..)` / `topic.cbor(..)` | A typed handle. `publish` encodes, `publish_batch` encodes many, `records(name)` opens a typed cursor |
| `topic.schema(id)` | A typed handle bound to a registered schema. Async in all three SDKs. Needs Laser Stack or LaserData Cloud, and Rust needs the `schema-codecs` feature |
| `topic.producer()` | A long-lived producer with batching, linger, and retries. See [Producing at volume](#producing-at-volume) |
| `topic.batching()` | A client-side accumulator with `flush()` and `close()`. See [Batching producers](#batching-producers) |
| `topic.consumer(..)` / `topic.consumer_group(name).consumer()` | A live consumer, partitioned across group members |
| `consumer.next()` / `next_within(timeout)` | Wait for the next record, optionally with a typed timeout |
| `consumer.commit(message)` | Commit after the record is handled |
| `store_offset(..)` / `delete_offset(..)` | Native consumers only |
| `topic.replay()` | A raw cursor from offset 0, or from saved offsets, across every partition |

An indexed header wins over a value that the projection schema extracts for the same field. A record with no indexed fields from headers or the schema produces no view row. [Queries and views](/laser-sdk/views) explains extraction and projection registration.

A typed publish through `topic.schema(id)` encodes Avro and JSON Schema bodies. For Protobuf, Rust and Python publish the encoded bytes with the schema ID, and TypeScript encodes the body.

`BatchPublishRequest.add_record` in Python takes per-record metadata. Batch defaults fill what the record leaves unset, and batch index entries and headers merge with the record's own, which win. Its `logical_schema_fingerprint=` parameter takes 32 bytes and needs Arrow content. TypeScript exposes the same metadata through `Record.logicalSchemaFingerprint(bytes)`. Use the Arrow IPC helpers when the SDK must check metadata and payload length.

- [Messages](/laser-sdk/log): The short guide with a quick example
- [Filters](/laser-sdk/consumer-filters): Deliver only matching records to a group
- [Connect](/laser-sdk/connect): Publish timeouts, retries, and reconnection
- [native-streaming example](https://github.com/laserdata/laser-sdk/tree/main/examples/rust/src/native-streaming): Tuned producer and both commit patterns in Rust, Python, and TypeScript

Source: https://docs.laserdata.com/laser-sdk/advanced/log
