Append records

Append records

Append records to a stream from Go, TypeScript, or HTTP, with a producer or in a single call.

You can append records in two ways. A producer keeps a session open and sends many batches in order, without waiting for each one; use it by default. A one-shot append sends one batch in one request; use it for an occasional write, or in a browser. Appends explains batches, the session window, and latency. Each example also has an HTTP tab. The API reference has the full append route, and the CLI has nova append.

Append with a producer

Use a producer for a steady flow of writes. It groups your records into batches and keeps several batches in flight. After a reconnect, it sends the batches that have no acknowledgement again, in order. OpenStream / openStream opens a producer, and creates the stream first when its bucket creates streams on append.

stream := client.Address{Bucket: "demo", Key: "events"}

p, err := c.OpenStream(ctx, stream)
if err != nil {
	return err
}
defer p.Close(ctx)

res, err := p.Append(ctx, client.Bodies([]byte("first"), []byte("second"))...)
if err != nil {
	return err
}

fmt.Println("records", res.Start.SeqNum, "to", res.End.SeqNum-1, "tail", res.Tail.SeqNum)
Output
records 0 to 1 tail 2

An append returns once Nova has stored its records. The result holds three positions. The start is the first record, the end is one past the last, and the tail is the end of the stream when Nova replied. Each position has a sequence number and a timestamp in milliseconds.

Keep appends in flight

Waiting for each append before you send the next one moves one batch per round trip. To write faster, start several appends and wait for them together. The producer sends them in the order you started them, and Nova stores them in that order.

var pending []<-chan client.AppendResult

for _, body := range []string{"third", "fourth", "fifth"} {
	done, err := p.AppendAsync(ctx, client.AppendRecord{Body: []byte(body)})
	if err != nil {
		return err
	}

	pending = append(pending, done)
}

for _, done := range pending {
	res := <-done
	if res.Err != nil {
		return res.Err
	}

	fmt.Println("stored at", res.Start.SeqNum)
}
Output
stored at 2
stored at 3
stored at 4

AppendAsync returns once the producer has taken the records, and the channel receives the result once Nova has stored them.

An append waits while the session window and the producer's buffer are full. Each call still gets back the positions of its own records, even when the producer sent them in one batch with others.

Tune batching

An idle producer sends each append at once. For many small records, ask it to wait a few milliseconds to fill a batch. You can also lower how much it keeps in flight.

p, err := c.OpenStream(ctx, stream,
	client.WithBatchLinger(5*time.Millisecond), // wait up to 5 ms to fill a batch
	client.WithInflightBytes(4<<20),            // at most 4 MiB in flight
)
if err != nil {
	return nil, err
}
WithBatchLingerLingerDefault0
Waits up to this long to fill a batch; at most 1 second
WithBatchSizeBatch sizeDefaultThe node's batch bound, 1 MiB
Stops filling a batch at this many bytes; above the node's bound, the open fails
WithInflightBytesIn-flight bytesDefaultThe node's session window: 48 MiB on Standard, 8 MiB on Express
Lowers the bytes sent and not yet acknowledged; at least one full batch
WithFencingTokenFencing tokenDefaultNone
Presents a token; see coordinate writers

A longer linger fills batches better and sends them later. Closing a producer never waits for the linger.

Close the producer

Close / close sends the records still buffered, waits for every acknowledgement, and ends the session. Give it a deadline:

// Wait at most ten seconds for the acknowledgements still due.
closeCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()

if err := p.Close(closeCtx); err != nil {
	return err
}

Closing the client ends its producers too, without waiting for their acknowledgements.

If the deadline passes first, the producer still closes, and the appends still waiting fail. An append it had not sent fails with ErrUnavailable / UnavailableError, and none of its records are stored. An append it had sent fails with ErrUnknownOutcome / UnknownOutcomeError, because Nova may have stored it. The stream is not affected: a new producer continues its sequence.

Append once

Use a one-shot append for an occasional write, such as in a request handler. It sends one batch in one request and returns once Nova has stored it. In a browser, it is the only way to append.

stream := client.Address{Bucket: "demo", Key: "events"}

res, err := c.Append(ctx, stream,
	client.AppendRecord{
		Body:    []byte(`{"id":1}`),
		Headers: []client.Header{{Name: []byte("type"), Value: []byte("order")}},
	},
	client.AppendRecord{Body: []byte(`{"id":2}`)},
)
if err != nil {
	return err
}

fmt.Println("records", res.Start.SeqNum, "to", res.End.SeqNum-1, "tail", res.Tail.SeqNum)
Output
records 0 to 1 tail 2

A record has a body, optional headers, and an optional timestamp (TimestampMs / timestampMs / timestamp_ms). The stream's timestamping rule decides what Nova does with your timestamp. When the bucket creates streams on append, the first append creates the stream.

The SDK checks a one-shot append against the batch bound a node last reported. Before any report, it uses the client options MaxBatchBytes and MaxBatchRecords / maxBatchBytes and maxBatchRecords, 1 MiB and 1,000 records by default. Set them if your nodes use other bounds and you only append one-shot.

Three more one-shot calls add a condition or a routing key:

Appends only
AppendMatchConditional
If the stream's next sequence number is the one you give (coordinate writers)
Presenting(token).AppendFenced
If the token is the stream's installed fencing token
AppendByKeyBy key
To the range of the routing key, on a scalable stream. Over HTTP, give each record the key in a nova-routing-key header

Producers have AppendMatch / appendMatch too, and a Go producer has AppendByKey.

When the outcome is unknown

An append fails with ErrUnknownOutcome / UnknownOutcomeError when it was sent and no reply came back. Its records may be stored. The SDK does not send it again, because a second copy would be a duplicate. Your code decides what to do.

To store a batch at most once, append it with a match sequence number, and on this error send the same append again:

// next is the sequence number this writer expects its records to get.
res, err := c.AppendMatch(ctx, stream, next, records...)
if errors.Is(err, client.ErrUnknownOutcome) {
	// The batch may be stored. Send it again with the same match:
	// the stream stores it at most once.
	res, err = c.AppendMatch(ctx, stream, next, records...)
}

if seq, ok := errors.AsType[*client.SequenceError](err); ok {
	// next is taken: by the first attempt, or by another writer.
	fmt.Println("not appended; the tail is", seq.Tail.SeqNum)
	return nil
}

if err != nil {
	return err
}

fmt.Println("records", res.Start.SeqNum, "to", res.End.SeqNum-1, "tail", res.Tail.SeqNum)
Output, run twice with the same next
records 0 to 1 tail 2
not appended; the tail is 2

Without a match, check the tail, read from your last known position, and look for your records before you send them again. Or accept a duplicate.

A producer also sends batches again on its own after a reconnect, without an error. A plain append on a producer can therefore be stored twice. A producer's AppendMatch / appendMatch prevents that too.

When an append is refused

For every other error, this table says whether the records were stored:

Error: Go, TypeScript, HTTPWhenStoredWhat to do
ErrBatchTooLarge, BatchTooLargeError, 400 with reason: batch_too_largeOne call holds more than one batch: 1,000 records or 1 MiB by defaultNoSplit it into several appends
ErrRecordTooLarge, RecordTooLargeError, 400One record holds more than 1 MiB or more than 64 headers, or Nova refused a record's headers or timestampNoFix the record. Put a large payload in object storage and append a pointer to it
ErrSequence, SequenceError, 412 with tailThe match sequence number was not the stream's next oneNo, unless Resent / resent is trueRead from the tail in the error, then decide
ErrFencedOut, FenceError, 412 with fencing_tokenThe fencing token is not the installed oneNoStop writing, or install a new token
ErrStreamNotFound, StreamNotFoundError, 404The stream does not exist, and its bucket does not create streams on appendNoCreate the stream
ErrNotAppended, NotAppendedErrorThe producer ended on an earlier batch's refusal before it read this oneNoAppend it again on a new producer
ErrUnavailable, UnavailableErrorNo node took the append within the retry budget, 30 seconds by defaultNoTry again later

The SDK refuses a batch or record that is too large before sending it, and the producer goes on. A refusal from Nova ends a producer, except a sequence error. After any other refusal, open a new producer. Handle errors lists every error.

An unknown outcome caused by an outage matches both ErrUnknownOutcome and ErrUnavailable, so test for ErrUnknownOutcome first. Use errors.As to read SequenceError.Tail or FenceError.Installed.

See also

On this page