TypeScript client
@timelake/client reads Timelake tables over HTTPS from the browser, Node, Bun, or serverless functions, and appends to them from the same places (Writing). A WebAssembly build of Timelake's reader (crates/timelake-wasm) parses the Iceberg metadata, prunes files and row groups, decodes Parquet, and computes aggregates. The package only fetches the byte ranges the reader asks for. There is no server and no query engine to run. Rows can be validated and typed with Zod.
import { z } from "zod"
import { Lake } from "@timelake/client"
const Reading = z.object({
time: z.coerce.date(), // times arrive as ISO strings
tags_id: z.number().int(),
velocity: z.number().nullable(),
})
const lake = new Lake("https://<store>.public.blob.vercel-storage.com/demo")
const readings = lake.table("tsbs.readings", Reading)
await readings.latest({ series: [1, 2, 3] }) // newest row per truck (last-value index)
await readings.range({ series: 7, from: "2026-01-03T12:00:00Z", to: "2026-01-03T13:00:00Z" })
const hourly = await readings.bucket({
series: 7, every: "1h",
agg: { velocity: ["avg", "max"], "*": ["count"] },
})
hourly[0].velocity_avg // number | null, typed from the agg mapInstall
npm install @timelake/client zodIt needs zod 4 as a peer dependency. Inside this repository it is a bun workspace package, and the website imports its TypeScript source.
What it reads
A warehouse served over plain HTTP(S), such as Vercel Blob, a public S3, R2 or GCS bucket, or a CDN. The server should support Range requests (it then answers 206); without them the client downloads whole files and still returns correct results. A plain HTTP server can't list files, so the client finds tables through the warehouse's timelake-tables.json, which the writer maintains (timelake index rewrites it).
The client asks for some objects that may not exist: the head, the version hint, and the next table version. It takes 404 and 403 both to mean the object is absent, because a public S3 bucket (or CloudFront in front of one) that grants only s3:GetObject answers 403 for a missing key. Any other error status fails the query.
API
| Call | Returns |
|---|---|
new Lake(url, { fetch?, concurrency?, cacheMs?, rewriteUrl? }) | A warehouse handle. concurrency caps parallel requests (default 16). cacheMs is how long a loaded table version is reused before checking for a newer one, in ms; without it, each table's version-check-interval setting decides (1 s unless the table sets it), as for the engine. rewriteUrl maps object URLs when a warehouse has moved. |
lake.tables() | string[] of namespace.table. |
lake.table(name, schema?) | A table handle. name is namespace.table, or table in the namespace default; both parts use [A-Za-z0-9_-], as in the engine. Rows are typed and validated with the Zod schema if one is given; otherwise they are Record<string, unknown>. |
table.latest({ series?, columns? }) | The newest row of each series, read from the last-value index in a single request. Tables without the index (written by another Iceberg writer) are scanned instead. |
table.range({ series?, from?, to?, columns?, limit?, order? }) | Rows in [from, to), ordered by time. columns narrows the result type to those columns. |
table.bucket({ series?, from?, to?, every, agg, by? }) | One row per bucket (and per by value): bucket: Date plus <column>_<op> for each aggregate (count, sum, avg, min, max, first, last); "*": ["count"] gives count. |
table.info() | Contract (timeColumn, seriesKey, chunk, dedup, ingestTimeColumn, retention), schema, snapshots (the newest 50 of snapshotCount), and live files of the current version. |
table.zodSource() | The TypeScript source of a Zod schema for the table, ready to paste. The schema is named after the table in PascalCase, without a trailing s unless it follows s, i or u (readings gives Reading, status gives Status). |
table.refresh() | Forget the cached table version, so the next query reads the newest one. |
zodSource(info, exportName?), readerVersion() | Standalone exports: generate Zod source from a table.info() result; the version of the embedded WASM reader. |
table.lastStats | Requests, bytes received, files, and milliseconds of the last query. Requests that loaded or checked the table version for it count too, so the first query on a handle counts the head and the version hint. |
series is a value or a list of values of the first series-key column, or an object such as { device_id: ["a", "b"] }.
Times are Date objects, epoch milliseconds, or ISO 8601 strings (2026-01-03T12:00:00Z, 2026-01-03 12:00, 2026-01-03). A string without an offset is UTC, as in the engine's SQL, so a query returns the same rows in a browser and on a server in another time zone. Strings keep microseconds (12:00:00.123456). Other date formats are an error.
Durations use the engine's syntax: a whole number and a unit, s, m, h, d, w or y (365 days), such as 30s, 10m or 1h, or spelled out (90 minutes, 1 day). A number is milliseconds, which is how to write a bucket shorter than a second. Buckets are aligned to the Unix epoch unless origin is given.
Writing
TableWriter appends to a table from JavaScript: a Cloudflare Worker, Node, Deno, Bun, or a browser. The WebAssembly module runs the engine's write path. It aligns rows to the table's schema, adds the insertion time, sorts by series and time, keeps the last of rows with the same series and time, and writes one Parquet file per time partition. Then it commits the way the engine does, and updates the last-value index and the head. The engine, DuckDB, and the reader above see the rows like any others.
import wasm from "@timelake/client/timelake.wasm"
import { TableWriter, initWasm, r2Store } from "@timelake/client/workers"
initWasm(wasm)
export default {
async queue(batch, env) {
// An R2 binding LAKE on the bucket that holds s3://my-bucket/lake.
const writer = new TableWriter(r2Store(env.LAKE), "s3://my-bucket/lake", "iot.readings")
const rows = batch.messages.map((m) => m.body) // { time, device, temp }
await writer.append(rows, { batchId: batch.messages[0].id })
},
}-
In Workers, import from
@timelake/client/workers, and pass the module from@timelake/client/timelake.wasmtoinitWasm. Workers can't compile WebAssembly from bytes at runtime, so the default entry, which embeds the module as base64, doesn't run there. Wrangler bundles the.wasmimport as a compiled module. Elsewhere (Node, Deno, Bun, browsers), the default@timelake/clientworks as is. -
Store. A writer reads and writes objects through a
Store:r2Storefor an R2 binding,memoryStorefor tests, or your own (get,getRange,put,putIfAbsent,list,delete, and optionallyuploadfor multipart uploads).putIfAbsentmust be atomic, because commits rely on it. The second argument is the warehouse root as the table metadata records it, and the third the table name (namespace.table, ortableindefault). Keys are what follows the bucket. -
Rows. Pass objects or an Arrow IPC stream. In objects, times are
Dates, ISO strings, or epoch milliseconds (millisecond precision). Use Arrow IPC for microseconds. Integers beyond 2^53 are written exactly asbigints; runtimes withoutJSON.rawJSON(ES2025) reject such abigintinstead of rounding it. A column the table doesn't have, or a missing required one, is an error, and nothing is written. -
Commits. A writer keeps the version it last committed, so a steady writer doesn't reload the table before each append. If another writer committed in between, the commit reloads and retries. A
batchIdmakes retries safe: an append whose batch id is already in the table is skipped. -
One writer per table works best: a Queues consumer or a Durable Object that collects rows into appends of a few thousand or more. Concurrent writers are safe, but each conflict costs a retry, and many small appends make many small files.
-
Creating tables. Create the table first with the CLI or Python. Writers can't create tables yet.
-
Memory and time in workerd (Cloudflare's runtime, run locally with Miniflare on a local R2 bucket; TSBS-like rows with 9 columns):
| Time | WebAssembly memory | |
|---|---|---|
| Append of 1,000 rows | 0.2 s | 5 MiB |
| Append of 100,000 rows | 0.7 s | 37 MiB |
| 60 appends of 1,000 rows with inline maintenance | 18 ms each (median), 0.2 s with compaction | 16 MiB |
| Compaction of a day of 24 files (1.2M rows, 47 MiB) | 2.7 s | 95 MiB |
A Worker has 128 MB of memory, WebAssembly included. Compaction reads each file a window of pages at a time, merges at most 24 files at once (larger groups in parts), and writes row groups of at most 16 MiB. Files written from JavaScript have data pages of 8,192 rows (the setting data-page-rows; the engine writes 20,000), since compaction holds a page per column of each file it merges. Method and details: bench/results/WORKERS.md.
- Maintenance. After each append, the writer runs what the engine runs inline. It merges size tiers of small files in the partitions the append touched, and rewrites cold partitions whole. It also applies retention and expires snapshots in batches. Compaction is a streaming merge: memory is about one row group per file being merged, not the partition. One append's compaction reads at most
maxCompactBytes(default 64 MiB), so it stays within a request's CPU time; what's left waits for the next append.writer.maintain({ maxBytes })runs a full pass, for example from a scheduled Worker; while its report saysmoreToCompact, another pass has more to merge. The report has the same fields as the engine's (timelake maintain, Python'smaintain()), in camelCase;rollupsRefreshedis always 0, since only the engine refreshes rollups.timelake maintainelsewhere is optional.
How a query runs
-
Read the table's head object (
metadata/timelake-head) andversion-hint.textat the same time. The head holds the metadata, the files, and usually the last-value index and file footers, so alatestquery needs no further request. A HEAD request for the next version runs alongside the query; if one exists, the result is dropped and the query reruns on the newest version. Tables without a head are read through the metadata, the manifest list, and the manifests. A loaded version is reused forcacheMs, or the table'sversion-check-intervalwithout it. After that, HEAD requests for the loaded version and the next one check for a newer version: maintenance deletes the oldest metadata files, so a missing loaded version also means a newer one exists.To find the newest version, the client asks for versions after the one it knows, doubling the step until a version is missing, then halving it, so a handle many commits behind needs a few requests, not one per commit. If the metadata it would start from was deleted, it starts again from the head and the version hint.
-
Prune data files on their Iceberg column bounds (time range, series key).
-
For each remaining file, take the Parquet footer from the head or fetch it, then fetch only the row groups and columns the query needs.
-
Decode, filter, and sort or aggregate in WebAssembly, and return JSON rows (validated with Zod if given).
Limits
- Writes are appends to existing tables (see Writing); creating tables and schema changes go through the CLI, the Python package, or the Rust library.
- It answers time-series query shapes, not arbitrary SQL. For SQL, use the engine (CLI, Python) or plain DuckDB.
- The WASM module is embedded as base64, about 8 MB of JavaScript (about 2 MB gzipped). That is fine on servers; in browsers, load it lazily.
- Pruning works at the row-group level. Tables meant for web reads should use smaller row groups (the demo uses
timelake.row-group-rows=65536). - Tables with delete files (row-level deletes another engine such as Spark or Trino wrote) are refused, for reads and writes: the client doesn't apply them, and the rows they delete would come back.