invalidate fetches one whole JSON document per key, which suits a dataset that fits in one response. For data that does not (a map with hundreds of thousands of points, a long server-side list), the optional, general-purpose entry live_slice/data loads it in chunks over plain HTTP and loads only what the current view needs. It has no runtime dependencies and knows nothing about maps; the tile grid helper for maps is in live_slice/maplibre.

Chunk loader

The app describes how a query (a viewport, a range of rows, a filter) maps to chunk keys, and how a chunk key maps to a URL. The loader fetches the chunks and publishes them to a store key:

import { createChunkLoader, pageChunks } from "live_slice/data";

const loader = createChunkLoader({
  store,
  key: "rows",
  statusKey: "rowsStatus",
  // query -> chunk keys, most wanted first: here the pages of 500 rows that {start, end} touches
  chunksFor: pageChunks({ pageSize: 500 }),
  url: (page, version) => `/api/rows?page=${page}&v=${version}`,
  // loaded chunks of the query, in query order -> the value stored under `key`
  combine: (values, keys) => values.flat(),
  version: 1,
});

loader.setQuery({ start: 0, end: 200 }); // later queries fetch only what is new
loader.status(); // {total, loaded, loading, errors, skipped, held, fromCache, fromNetwork}
loader.destroy(); // when the hook goes
  • Only missing chunks are fetched. A query that overlaps the previous one fetches only the chunks the loader does not hold, and a chunk already being fetched is never fetched twice. Requests of chunks the query no longer needs are aborted, and a reply that still arrives for them is ignored. At most concurrency (4) requests run at once, in the order chunksFor returned the keys.
  • Bounded memory. At most maxChunks (64) chunks are held, and the least recently used ones that the current query does not need are evicted first. A query of more than maxChunks chunks loads only its first maxChunks and reports the rest as skipped, with one console.warn. The loader calls chunksFor(query, {limit}) with limit set to maxChunks: a chunksFor may list only the first limit keys and give the number of the others as a skipped property of the array it returns (a non-negative integer), which status().skipped includes. pageChunks does, so a huge range costs no more than a small one.
  • Batched publishing. Chunks that arrive before the scheduled publish (the next animation frame, or a timer after 100 ms when no frame comes, as in a hidden tab) make one store update, so subscribers are not called once per chunk. Partial results are published as chunks arrive. combine(values, keys) is called only when the set of loaded chunks of the query changed; it runs again for every partial result, so keep it cheap: build what each chunk needs once (for example in a WeakMap keyed by the chunk value) and only join the parts in combine. Without combine, the value is an object of chunk key to chunk value, in query order. schedule(publish) replaces the scheduler; it may return a function that cancels it.
  • The chunks themselves. With chunksKey, the loader also publishes the loaded chunks of the query as {keys, values} (their keys and decoded values, in query order), in the same store update as key and only when that set changes. Code that scans every record reads them there instead of keeping its own copy (see Reading the loaded chunks). key becomes optional: a loader with only chunksKey builds no combined value, and refuses a combine.
  • Keeping the previous value. By default, a query that shares no chunk with the previous one (a map crossing a zoom level) or a new version publishes what it holds at once: nothing, until its first chunk arrives. With keepPrevious: true, the value published last stays until one chunk of the new query has loaded (or none is still loading: every chunk failed, or the query needs none), so a map keeps its points instead of blinking empty; so do the chunks under chunksKey. The status follows the new query all the same. It is off by default because a paged list would then show the rows of another page under the new one's position.
  • Failures. A failed chunk (network error, non-2xx status, refused URL, a decode that throws) is reported with console.error and in status().errors as {chunk, message}; the other chunks are published all the same, and the next setQuery that needs it fetches it again.
  • Status. status() returns plain JSON: total, loaded and loading count the chunks of the current query, errors lists its failed ones, skipped the ones beyond maxChunks, held the chunks in memory, and fromCache and fromNetwork the chunks served by the persistent cache and by the network since the loader was created. With statusKey, it is published in the same store update as the data.
  • Versions. version (a string, a number or null) is passed to url. setVersion(next) drops the held chunks, aborts the requests in flight and loads the current query again; the same version changes nothing. With versionKey instead of version, the version is the value of that store key and follows its changes; nothing is loaded while it holds null (see Dataset versions). key, chunksKey, statusKey and versionKey must be different keys (a TypeError otherwise).
  • Decoding. decode(response, chunk) turns a successful response into the chunk value (it may return a promise); the default jsonDecoder parses JSON. A decoder's accept property, when set, is sent as the accept header.
  • URLs. Chunk URLs follow the policy of invalidate: only http: and https: URLs of the page's origin are fetched, relative URLs resolve against the page, and allowUrl(url) is asked about any other URL. A refused URL fails its chunk. fetch replaces the global fetch, and baseUrl the page's URL (in a worker or a test).

The loader writes its value with store.setState, so it is confirmed (base) state, like a server patch: pending server actions stay applied on top of it. Large values must not travel through the mirror or the store's persisted record, so createChunkLoader throws a TypeError when key or chunksKey is one of the store's persist.keys (store.persistedKeys lists them) or when a bridge element on the page mirrors it. The mirror check only sees the bridges rendered when the loader is created: never list a loader's keys in :mirror. Mirror the query instead (a viewport, a page), which is small.

Chunk schemes

Two helpers build chunksFor for common schemes:

import { pageChunks } from "live_slice/data";
import { tileChunks } from "live_slice/maplibre";

// Rows in pages: {start, end} (end excluded) -> the page keys "0", "1", ... it touches.
pageChunks({ pageSize: 500, total: 50_000 });

// A map viewport -> the "z/x/y" keys of the Web Mercator tiles its bounding box touches.
tileChunks({ zoomFor: (viewport) => viewport.zoom - 1, minZoom: 2, maxZoom: 10, maxTiles: 32 });
  • pageChunks({pageSize, total}): with total, rows from total on do not exist. No query (null) or an empty range needs no page. Given a limit (the loader passes its maxChunks), it lists only the first limit pages and counts the others in the array's skipped property.
  • tileChunks({zoom, zoomFor, minZoom, maxZoom, maxTiles}) lives in the MapLibre entry, since it is about maps, but uses no map: the viewport is a bbox [west, south, east, north] or an object with such bounds (as bindMap's default viewport). The tile zoom is zoom, zoomFor(viewport) or the viewport's zoom, rounded down and clamped to [minZoom (0), maxZoom (22)]. Latitudes are clamped to the Web Mercator range, and a bbox across the antimeridian (west > east, or longitudes beyond ±180) takes the tiles on both sides. When the bbox needs more than maxTiles (64) tiles, the zoom is lowered until it needs at most that many; at minZoom only the maxTiles nearest the center are kept, found without listing the others, so a world view at a high minZoom costs no more than a small one. Tiles come from the center outwards, so the middle of the view loads first. A bbox that spans every column keeps its own center (a world view centered on the Pacific keeps the Pacific), with distances measured the short way around.

Dataset versions

The server tells loaders about a new version of a dataset through the bridge, without a new event: it patches a small store key, and the loader follows that key with versionKey:

# On mount, and whenever the dataset changes (to every LiveView showing it, through PubSub)
socket |> LiveSlice.patch(:map, %{featuresVersion: Features.version()})
createChunkLoader({ store, key: "features", versionKey: "featuresVersion", ...options });

Until the key holds a version, the loader fetches nothing, so a page does not load chunks of an unknown version first. That includes the persistent cache: after an offline start the server has not patched the key, so a loader whose versionKey the store does not persist loads nothing at all, cached chunks included. Persist the key (persist: { keys: ["featuresVersion"] }) to load offline; a loader created with a cache and a versionKey that is not in persist.keys says so with console.warn. A chunkVersionsKey (see Per-chunk versions) should be persisted too, or offline the cache is read without the chunks' own versions. A new version drops the held chunks, aborts the requests in flight, prunes the cache entries of other versions and loads the current query again. Put the version in the chunk URLs too, so HTTP caches never serve an old chunk for a new version. invalidate/4 stays the tool for a dataset fetched as one document.

The server must answer a chunk URL with exactly the version it names, or refuse it with an error status (the demo answers 409 Conflict with the current version): the loader caches what it receives under the version it asked for, so current bytes served for an old version's URL would stay in the cache as that version, and a page still on it would read them later. A refused chunk is a failed chunk: it is not cached, and the next setQuery that needs it asks again, usually after the server's patch of the new version has arrived.

Per-chunk versions

The dataset version drops every chunk. When the server knows which chunks changed (one tile of a map after an edit), it gives those chunks a version of their own, in a store key that maps chunk keys to versions, and the loader fetches only them again:

# One entry of the map key, without resending the others (see Patching entries)
socket |> LiveSlice.put_entries(:map, :tileVersions, %{"7/64/42" => changed_at})
createChunkLoader({
  store,
  key: "features",
  versionKey: "featuresVersion",
  chunkVersionsKey: "tileVersions", // or chunkVersions: {...} and loader.setChunkVersions({...})
  url: (tile, version, tileVersion) => `/tiles/${tile}?v=${version}&t=${tileVersion ?? 0}`,
  ...options,
});
  • url(chunk, version, chunkVersion) receives the chunk's own version as a third argument (null for a chunk without one), so the URL changes with it and no HTTP cache serves the old bytes.
  • A chunk whose version changes is fetched again, the others stay; until the new one arrives, the value held so far keeps showing. A request in flight for the old version is aborted.
  • The persistent cache keeps a chunk under its key and its own version, so a reload reads the new version from the cache once it was fetched, and never reads the old one for the new version. Entries of old chunk versions stay in the cache until the dataset version changes (prune) or the cache's size budget evicts them.
  • versionKey works as before, and a new dataset version still drops everything; give chunk versions that are unique within a dataset version.

Persistent chunk cache

createChunkCache keeps chunks across reloads in IndexedDB, in a database of its own (live_slice_chunks), apart from the stores' persisted records. With a cache, the loader serves a chunk from memory first, then from the cache (one read for all the missing chunks of a query), then from the network, and writes what it fetched back in batches:

import { createChunkCache, createChunkLoader } from "live_slice/data";

const cache = createChunkCache({ maxBytes: 50 * 1024 * 1024, maxEntries: 2000 });
const loader = createChunkLoader({ ...options, cache, name: "features", version: 3 });
  • Values are stored with the structured clone algorithm, so typed arrays and ArrayBuffers round-trip as they are, without JSON. A value that cannot be cloned is skipped.
  • Versions. An entry matches only the loader's current version and the cache's own version (1 by default; bump it when the shape of decoded values changes). When the loader starts with a version, or setVersion changes it, the loader prunes the entries of its scope with any other version. A reload with the same version serves the chunks from IndexedDB without a request; a new version fetches them again.
  • Bounds. At most maxEntries entries (unbounded by default) and maxBytes estimated bytes (50 MiB by default). A write that goes beyond either removes the least recently used entries (by last read or write) in the same transaction, and a single value larger than maxBytes is not stored. The size is an estimate (estimateSize): the byte length of each ArrayBuffer (a typed array counts its whole buffer, once per buffer, as structured clone stores it) and of each Blob, plus about the JSON length of everything else, the keys and values of a Map and the values of a Set included. It is not what the browser uses on disk, and the browser's quota can still refuse a write.
  • Scopes. Entries are keyed by the loader's name (JSON.stringify([storeName, key]) by default, so dots in names cannot make two loaders share a scope) and the chunk key, so loaders can share a cache; give each its own name. Eviction is global to the cache.
  • Failures degrade to no cache. A read that fails, or takes longer than readTimeout (1 s), misses; a write that fails stores nothing; the first failure is reported with console.error. As in the store's storage, a connection closed by another tab or the browser is opened again, and an open blocked by another tab waits at most blockedTimeout (10 s). The loader never fails because of its cache.
  • Tabs share the database. Every write, with its eviction, is one readwrite transaction, which IndexedDB runs one at a time, so the totals and the bounds hold. Reads update the last-used stamps afterwards, only for entries still there, so a tab may evict an entry another tab has just read (that tab already holds the value in memory).
  • cache.usage() resolves with {entries, bytes}, cache.clear() removes every entry (for example when another user signs in), and cache.prune(scope, version) removes the entries of a scope with another version. Any object with read(scope, keys, version) (resolving with a Map of the hits) and write(scope, entries, version) works as a cache.

Binary columns

JSON is a heavy format for large lists of flat records. LiveSlice.Columns encodes them on the server in a small binary columnar format, and decodeColumns (or columnsDecoder, as the loader's decode) reads it in the browser:

# A controller action serving one chunk
conn
|> put_resp_content_type(LiveSlice.Columns.content_type(), nil)
|> send_resp(200, LiveSlice.Columns.encode(points, id: :uint32, lon: :float32, lat: :float32, kind: :dict))
import { columnsDecoder, createChunkLoader, decodeColumns } from "live_slice/data";

createChunkLoader({ ...options, decode: columnsDecoder });
// each chunk value: {count, names: ["id", "lon", "lat", "kind"],
//   columns: {id: Uint32Array, lon: Float32Array, lat: Float32Array, kind: string[]}}
  • Types: :float64, :float32 (rounded to the nearest float32; out of its range is refused), :int32, :uint32, :int16, :uint16 (2 bytes per value; Int16Array and Uint16Array in the browser), :uint8, :dict (strings stored once in a dictionary plus one index per record, for columns with few distinct values) and :utf8 (strings one after the other, with offsets). No nil values. A dictionary holds strings only: a numeric column with few distinct values is smaller as :uint8 or :uint16 codes, with no dictionary to send, mapped to their meaning on the client. Building a dictionary checks each distinct string once for UTF-8, not each record: 100,000 records encode in about 8.5 ms with 12 distinct values and 9.1 ms with 2,000 (14.8 ms and 17.6 ms before; demo/bench/columns_dict.exs, on the development machine).
  • Input: a list of records (maps with the schema's keys, atoms or strings) or a map of columns. In the map form, a numeric column may be a binary that already holds its values little-endian, such as a binary_part/3 of a larger column kept in memory: it is passed through without copying.
  • Output: numeric columns decode to typed-array views into the response body, without copying (a typed array input whose offset is not 8-byte aligned is copied first). dict and utf8 columns decode to arrays of strings. names lists the column names in the order of the data: read the columns in order through it, since an object lists integer-like keys ("10", "2020") first whatever their order. LiveSlice.Columns.decode/1 is the inverse on the server, for tests.
  • Validation: the decoder checks every count and length against the buffer before reading, and throws an Error starting with live_slice: invalid columns data for anything that does not follow the layout exactly: wrong magic or version, truncation, trailing bytes, non-zero padding, offsets that go down, dictionary indexes out of range, invalid UTF-8, unknown types, empty or duplicate names. A chunk that fails to decode fails alone, like any other failed chunk.

The byte layout, little-endian throughout:

OffsetSizeField
04magic LSCF
41format version, 1
53reserved, zero
84record count N (uint32)
124column count C (uint32)
16...C descriptors: type (uint8: 1 float64, 2 float32, 3 int32, 4 uint32, 5 uint8, 6 dict, 7 utf8, 8 int16, 9 uint16), name length L (uint8, 1 to 255), name (L bytes of UTF-8, unique)

Then one data section per column, in descriptor order, each starting at a multiple of 8 (zero padding before it), so every numeric array is aligned for a typed-array view:

  • float64: N x 8 bytes; float32, int32 and uint32: N x 4 bytes; int16 and uint16: N x 2 bytes; uint8: N bytes.
  • dict: the entry count D (uint32); D + 1 offsets (uint32) into the string bytes, from 0 and never decreasing; the UTF-8 bytes of the entries; zero padding to a multiple of 4; N indexes of 1 byte when D <= 256, 2 bytes when D <= 65536, 4 bytes otherwise.
  • utf8: N + 1 offsets (uint32), from 0 and never decreasing; then the UTF-8 bytes of the values.

The data ends right after the last section. The same layout is specified in the moduledoc of LiveSlice.Columns; assets/test/fixtures/columns.bin is written by the Elixir tests and decoded by the JavaScript ones, and assets/test/fixtures/columns_dict.json holds the size and SHA-256 of what the Elixir encoder writes for dictionaries on each side of the 1-, 2- and 4-byte index thresholds, which the JavaScript tests encode again from the specification and decode.

Reading the loaded chunks

combine builds one value for the whole query. Code that scans every record (an aggregate, a table computed in the browser) is better served by the decoded chunks themselves, which the loader publishes under chunksKey:

import { columnsDecoder, createChunkLoader, pageChunks } from "live_slice/data";

// Sales in pages of 50,000 rows, as binary columns: {count, names, columns: {region: string[], amount: Float64Array}}
const loader = createChunkLoader({
  store,
  chunksKey: "salesChunks", // no `key`: nothing is combined
  statusKey: "salesStatus",
  versionKey: "salesVersion",
  chunksFor: pageChunks({ pageSize: 50_000, total: 1_000_000 }),
  url: (page, version) => `/api/sales?page=${page}&v=${version}`,
  decode: columnsDecoder,
});
loader.setQuery({ start: 0, end: 1_000_000 }); // the 20 pages

// Totals per region in one pass over the columns, without an object per row.
store.subscribe(
  (state) => state.salesChunks,
  (chunks) => {
    const totals = new Map();
    for (const { count, columns } of chunks?.values ?? []) {
      const { region, amount } = columns;
      for (let i = 0; i < count; i++) totals.set(region[i], (totals.get(region[i]) ?? 0) + amount[i]);
    }
    store.setState({ salesByRegion: Object.fromEntries(totals) }); // small: may be mirrored
  },
);
  • What it holds. {keys, values}: the keys of the loaded chunks of the query and their decoded values, in query order. The values are the objects the loader holds, whether they came from the network or from the persistent cache; nothing is copied, so treat them as read-only (a write into a typed array changes what every reader sees). The object and its two arrays are frozen.
  • When it changes. In the same store update as key and statusKey, and only when the set of loaded chunks changed, partial results included: while chunks are still loading, a subscriber sees only the loaded ones (statusKey says how many are missing). It never holds chunks of another query or version, except with keepPrevious, which keeps the previous ones as it keeps the value under key. Until the first chunk loads, the key keeps the store's own value (null above).
  • Both keys. A loader may publish both: the demo's map loader puts one GeoJSON source under features for MapLibre and the decoded tiles under featureTiles, from which the table of /map-client is computed. Like key, the value stays in the store when the loader is destroyed, so a hook mounted later (after a live navigation) reads it at once.

Measurements

Measured on the demo's synthetic dataset (200,000 points scattered around 14 cities, Demo.Features). The data is synthetic: your own data will compress, encode and decode differently, so measure it before deciding. Each payload is per tile, as the map hook fetches it; the GeoJSON of a tile holds the same points and properties as its binary tile (id, name, category, city, value), with coordinates rounded to 5 decimals, where the binary tile holds float32 coordinates (both about a metre). The binary tiles use uint32 for the id and value, float32 for the coordinates and dict for the category and the city; the name is rebuilt in the browser from the city and the id.

cd demo
mix run --no-start bench/large_data.exs   # sizes and server encode times; writes tmp/bench/
node assets/bench/decode.mjs tmp/bench    # Node decode times of the same payloads

Server side (Elixir 1.16.2, OTP 26). Sizes in MB (10^6 bytes) summed over the tiles, times in ms (median of 5, each tile encoded in a process of its own), GeoJSON encode including building the maps from the columns:

PayloadRecordsGeoJSONGeoJSON gzipBinaryBinary gzipEncode GeoJSONEncode binary
one tile (3/4/2)357386.290.670.640.36254.69.3
the initial view (4 tiles at zoom 3)9013515.961.691.620.92590.026.9
the whole dataset (64 tiles at zoom 3)20000036.093.743.612.031206.353.8

Decoding in Node 24.19.0 (ms, median of 5). Node timings are not browser timings: same engine family, but not the browser's load, and none of the map's own work (MapLibre indexes a GeoJSON source in its worker whichever format the data came in). The last column is what the map hook does: decode, then build the GeoJSON features its source needs.

PayloadRecordsJSON.parse GeoJSONdecodeColumnsdecodeColumns + GeoJSON features
one tile (3/4/2)3573830.60.68.9
the initial view (4 tiles at zoom 3)9013564.11.217.9
the whole dataset (64 tiles at zoom 3)200000129.32.125.8

In the browser (headless Chromium 159 over the DevTools protocol, demo served on localhost, one run; the check script is not part of the repository):

WhatMeasured
First load of /4 tiles at zoom 3, 90,135 points, 1,624,104 bytes transferred (Phoenix does not compress the tiles)
Decode of those 4 tiles in the pagedecodeColumns 0.84 ms; JSON.parse of the same points as GeoJSON (15.96 MB of text) 39.5 ms
A pan that brings one new column of tiles into view2 tile requests (258,674 bytes), none for tiles already held; 100 ms from the viewport change to the new tiles published (373 ms in an earlier run)
Reload0 tile requests: the 4 tiles came from IndexedDB
New dataset version4 tile requests, all under the new version
Cache after the first load4 entries, 3.19 MB estimated: decoded values, whose dictionary columns are arrays of strings

Machine: a shared WSL2 Linux machine under memory pressure, with other workloads running; expect other numbers elsewhere. gzip sizes assume something compresses the responses (a reverse proxy or a CDN): Phoenix does not compress dynamic responses by default.

Limits

  • No server-side index. The library does not index or tile your data. The demo sorts its points by quadkey so that a tile is one range of ids, which is enough for static synthetic points; real data needs its own index (a database with a spatial index, PostGIS, precomputed files).
  • No vector tiles. The chunks are app-defined data, not Mapbox vector tiles or PMTiles; for those, use MapLibre's own sources.
  • Chunks are replaced whole. A change to one record inside a chunk is not patched in place: publish a new version (every chunk is fetched again) or choose chunks small enough that the app can invalidate them through a version in their URL.
  • Memory is bounded in chunks, not bytes. maxChunks counts chunks; their size is up to the app. The combined value (for example one GeoJSON source of every loaded tile) is rebuilt for every partial result (a loader with only chunksKey builds none), and a map source of hundreds of thousands of features is heavy for the browser whatever the transport.
  • Cache quota. maxBytes bounds an estimate. The browser may still refuse a write when the origin is over its quota, or evict the whole database under storage pressure (and Safari can clear script-written storage of sites not visited for a while). The loader then fetches from the network; nothing is lost but time. The cache stores decoded values, so a format that decodes to bigger values (strings) takes more room than its wire size; a decode that returns the raw ArrayBuffer, with decoding in combine (memoized per chunk), stores the compact form instead.
  • Failures are retried by the next query, not on a timer. There is no backoff or automatic retry.
  • Tabs do not share memory. Each tab holds its own chunks; they share only the persistent cache.