Changes
Get told when a view advances, so you query only when there is new data
The change feed tells you when a view advanced. Instead of re-running a query on a timer, you poll a small feed and query only when the view moved. Use it for live dashboards, cache invalidation, and agents that react to new data. It needs Laser Stack or LaserData Cloud.
Quick example
This assumes the readings_v1 binding from Queries and views with notify() added to the binding builder. The program opens a reader at the end of the feed, publishes a reading, waits for the view to move, then queries it.
import { Laser } from "@laserdata/laser-sdk"
await using laser = await Laser.connectEnv()
// Start at the end of the feed, so only changes after this point arrive.
const feed = await laser.watch().index("readings_v1").fromEnd().records()
await laser
.stream("telemetry")
.topic("readings")
.publish()
.json({ host: "node-7", cpu: 82, status: "degraded" })
.send()
const changes = await feed.pollWithin(10_000)
for (const { change } of changes) {
console.log(`${change.rows} row(s), offsets ${change.fromOffset}..${change.toOffset}`)
}
const latest = await laser.query("readings_v1").whereEq("status", "degraded").fetch()
console.log(`${latest.rows.length} degraded readings`)use laser_sdk::prelude::full::*;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), LaserError> {
let laser = Laser::connect_env().await?;
// Start at the end of the feed, so only changes after this point arrive.
let mut feed = laser.watch().index("readings_v1").from_end().records().await?;
let reading = serde_json::json!({"host": "node-7", "cpu": 82, "status": "degraded"});
laser
.stream("telemetry")
.topic("readings")
.publish()
.json(&reading)?
.send()
.await?;
let changes = feed.poll_within(Duration::from_secs(10)).await?;
for watched in &changes {
let change = &watched.change;
println!("{} row(s), offsets {}..{}", change.rows, change.from_offset, change.to_offset);
}
let latest = laser
.query("readings_v1")
.where_eq("status", "degraded")
.fetch()
.await?;
println!("{} degraded readings", latest.rows.len());
Ok(())
}import asyncio
import laser_sdk as ls
async def main() -> None:
async with await ls.Laser.connect_env() as laser:
# Start at the end of the feed, so only changes after this point arrive.
feed = await laser.watch(index="readings_v1", from_end=True)
await laser.stream("telemetry").topic("readings").publish(
{"host": "node-7", "cpu": 82, "status": "degraded"}
).send()
for watched in await feed.poll_within(10_000):
change = watched.change
print(f"{change.rows} row(s), offsets {change.from_offset}..{change.to_offset}")
latest = await laser.query("readings_v1").where_eq("status", "degraded").fetch()
print(f"{len(latest.rows)} degraded readings")
asyncio.run(main())package main
import (
"context"
"fmt"
"os"
"time"
"github.com/laserdata/laser-sdk/foreign/go/laser"
"github.com/laserdata/laser-sdk/foreign/go/wire"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if err := run(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
client, err := laser.ConnectEnv(ctx)
if err != nil {
return err
}
defer client.Close()
// Start at the end of the feed, so only changes after this point arrive.
feed, err := client.Watch().Index("readings_v1").FromEnd().Records(ctx)
if err != nil {
return err
}
reading := map[string]any{"host": "node-7", "cpu": 82, "status": "degraded"}
if _, err := client.Stream("telemetry").Topic("readings").Publish().JSON(reading).Send(ctx); err != nil {
return err
}
changes, err := feed.PollWithin(ctx, 10*time.Second)
if err != nil {
return err
}
for _, watched := range changes {
change := watched.Change
fmt.Printf("%d row(s), offsets %d..%d\n", change.Rows, change.FromOffset, change.ToOffset)
}
latest, err := client.Query("readings_v1").Where("status", wire.StringTyped("degraded")).Fetch(ctx)
if err != nil {
return err
}
fmt.Println(len(latest.Rows), "degraded readings")
return nil
}A change record says which index moved, over which source offsets, and how many rows landed. It does not carry the rows. Query the index to read them. Each change also carries its message id and its position on the feed. A change published again after a retry keeps its message id, so drop a copy you have already handled by that id.
Watch every view
Leave out the index to read changes for every notifying binding on one feed: laser.watch().records() in Rust and TypeScript, await laser.watch() in Python. Each change's index field says which view moved.
Resume after a restart
Save the reader's offsets while it runs. After a restart, open a new reader and restore them. Without restored offsets, a new reader starts at the first change the feed still retains, or at its end with from_end.
const saved = feed.offsets // ReadonlyMap<number, bigint>
// After a restart
const resumed = (await laser.watch().index("readings_v1").records()).fromOffsets(saved)
// Changes retention removed before the reader reached them.
if (resumed.missed > 0n) await laser.query("readings_v1").fetch()let saved: Vec<u64> = feed.offsets().to_vec();
// After a restart
let mut resumed = laser
.watch()
.index("readings_v1")
.records()
.await?
.from_offsets(saved);
resumed.poll().await?;
// Changes retention removed before the reader reached them.
if resumed.missed() > 0 {
laser.query("readings_v1").fetch().await?;
}saved = feed.offsets # list[int]
# After a restart
resumed = await laser.watch(index="readings_v1", from_offsets=saved)
await resumed.poll()
# Changes retention removed before the reader reached them.
if resumed.missed:
await laser.query("readings_v1").fetch()saved := feed.Offsets() // one offset per partition
// After a restart
resumed, err := client.Watch().Index("readings_v1").Records(ctx)
if err != nil {
return err
}
if _, err := resumed.FromOffsets(saved).Poll(ctx); err != nil {
return err
}
// Changes retention removed before the reader reached them.
if resumed.Missed() > 0 {
if _, err := client.Query("readings_v1").Fetch(ctx); err != nil {
return err
}
}Store the saved offsets wherever your application keeps state, such as a file or key-value state.
Good to know
- Turn the feed on per binding with
notify(). A binding without it sends no change records. - Notifications are best effort. A lost one does not lose data, because the rows are already in the view.
- The feed shows that a view moved. To be sure a query includes your own write, use a read-your-writes query.
- The SDK does not push.
poll()returns at once, andpoll_within(TypeScriptpollWithin) reads again until a change lands or the timeout passes. - If the feed's retention removed changes before a resumed reader reached them, the reader's
missedcount is above zero. Read the view again instead of trusting the feed. - A change record from a newer server version stops the reader at that record with a version-skew error, so an older client never misreads it. Upgrade the client.
- The index filter runs in the client. Use the same client setup, including the default stream, that you query with.
- On a deployment without the feed, opening the reader returns an unsupported error. Opening a reader checks the capabilities again, so a deployment that starts publishing the feed after you connected is seen.