Repository navigation
In 0.6, two inserts of the same _id could both report success. An update could bring back a row you'd just deleted. A collection could keep accepting writes after compaction stopped making progress, leaving reads to get slower as the log grew.
I'd written a blog post about why silent failures were worse than explicit errors. Then I shipped several.
0.7.0 fixes those cases, makes capacity limits explicit, and removes some machinery that wasn't earning its keep. It also breaks a few APIs. The bucket format is unchanged; the application changes are below.
Upgrading
pnpm add @gusto/baerly-storage@0.7.0Back up first. baerly admin dump exports collection rows. Files your application writes directly to the bucket need a separate copy or bucket versioning.
There are three rollout details to read before deploying:
- All writers to a collection must run 0.7.0 before you can rely on the new concurrency guarantees. Older writers don't enforce them.
- 0.7.0 stops writing index markers. A 0.6.0 process reading after a 0.7.0 write can miss rows in indexed queries. This affects mixed deployments and rollbacks. Keep
index/while rollback remains possible, and read the upgrade guide's index marker section. - If you use R2 through the S3 API, maintenance has been failing in 0.6.0 too. The first maintenance pass after upgrading folds the backlog. The R2 binding is unaffected.
The runtime requirement is now Node 26 or later. On Workers Paid, set BAERLY_MAINTENANCE_PROFILE=cf-paid; a Worker can't detect its plan and defaults to Free limits. Workers Free with S3 over HTTP is no longer supported. Use Workers Paid with that setting, or the R2 binding.
Application and integration changes
| If you use… | Change in 0.7.0 |
|---|---|
err.code === "Conflict" |
Use WriteConflict for retryable conflicts and AlreadyExists for duplicate inserts. retriable is derived from the error code. |
Positional optional arguments to BaerlyError |
Use an options object: new BaerlyError(code, msg, { cause }). |
An exhaustive BaerlyErrorCode switch |
Remove Conflict. Add WriteConflict, AlreadyExists, AmbiguousCommit, CapacityExceeded, MaintenancePending, CursorExpired, and UnsupportedMediaType. |
Values such as Date, Map, NaN, or undefined array entries |
Convert them explicitly to plain JSON before writing. They are now rejected rather than coerced. |
| Non-string or non-NFC IDs; non-NFC app, tenant, or collection names | Validate and normalize at the application boundary. _id must be a well-formed NFC string. |
Duplicate insert calls as upserts |
Duplicate inserts now throw AlreadyExists. Use update or replace as appropriate. |
Patches typed as Partial<T> |
Use the exported MergePatch<T> type. Patches follow RFC 7396 at every depth. |
Declared indexes |
Declarations are still validated, but do nothing in 0.7.0. rebuild-index has been removed. |
A custom Storage implementation |
Remove versionId, conditional GET, and lastModified. Throw WriteConflict when a precondition fails. |
| The HTTP API directly | Send a JSON Content-Type on POST, PATCH, and PUT, or receive 415. On a 410 CursorExpired from /v1/since, restart with cursor: "". |
JWTs without exp |
bearerJwt and cloudflareAccess now reject them with 401. Configure an expiry at your identity provider. |
runScheduledMaintenance or undocumented exports |
/maintenance now exports one function, addressed by collection; undocumented internals have been removed from the package exports. See the upgrade guide for replacements. |
The upgrade guide groups changes by application, host, and data. The changelog has before-and-after examples for every breaking change. If the prose and shipped .d.ts files disagree, use the types.
Capacity limits now stop writes
In 0.6, a collection could exceed its host's compaction limit while continuing to accept writes. Maintenance stopped keeping up, but the log kept growing. The warning was a counter you had to know to watch.
0.7.0 refuses writes that would grow a collection past its host's limit. The errors distinguish a collection that needs less data from one that needs maintenance:
| Error | Meaning | Recovery |
|---|---|---|
CapacityExceeded — HTTP 409, not retryable |
The write would exceed the collection's capacity limit. Nothing is committed. | Make room or move to a host with a larger limit. Reads, deletes, and shrinking updates remain available, subject to request budgets. |
MaintenancePending — HTTP 503, retryable |
Folding pending changes would make room for the write. The write was refused. | Retry after the indicated delay. Each retry performs another fold pass; the bundled client handles this. |
Capacity is checked against the current collection state on every request. There is no stored read-only flag to clear after making room.
Writes nearing the limit carry a Baerly-Capacity-Warning header. The HTTP client exposes it through onWarning, and logs include capacity_warning.
Requests also have a storage-call budget. Retries and LIST pages count toward it. A request that cannot fit is refused with CapacityExceeded; a read is never shortened to fit the budget.
Host profiles now have separate fold limits. Node can fold up to 32 MiB / 65,536 rows; Workers Paid, 8 MiB / 32,768 rows. Previously, all profiles inherited the Free limits, with an arithmetic bug making Node's limit lower still. See scale-ceilings.md for the full limits.
Refusals log at warn with outcome: "refused". Alert on error.code: four codes share HTTP 409. Capacity refusals aren't counted as conflicts, and maintenance refusals aren't counted as errors.
Concurrent writes
Concurrent inserts of the same _id now have at most one winner. The first commit keeps the row; competing inserts throw AlreadyExists and commit nothing. Previously, both could report success while one silently replaced the other's document.
An update that races another write now applies its patch to the newest committed version of the row. It preserves concurrent changes to other fields and leaves a concurrently deleted row deleted. Previously, it could write back the version it first read, losing changes or resurrecting the row. A patch also cannot change _id.
When the outcome of a commit cannot be established from durable state, the operation returns AmbiguousCommit (HTTP 409, not retryable). It no longer reports success or suggests a blind retry. Read the row identified by err._id to reconcile the result. For an insert, retrying with the same _id is the safe recovery.
Auto-ID inserts through the HTTP client now get a UUIDv7 before sending. Resending the request replays the original success rather than creating another row. Other requests that are safe to resend get up to three attempts with jittered backoff; the client honors Retry-After up to 10 seconds.
Writes accept plain JSON
A document must be plain JSON, no larger than 1 MiB or 100 levels deep, with a well-formed NFC string for _id. The same validation runs in-process, in the HTTP client before sending, and during baerly admin restore.
Previously, JSON.stringify supplied some undocumented policy: a Date became a string, a Map became {}, and NaN became null. A numeric _id could be replaced with a UUID. These inputs are now rejected before I/O, with an error identifying the path and an err.resolution describing the remedy.
Invalid values and oversized documents produce InvalidConfig; excessive depth produces SchemaError. get(id) also throws InvalidConfig for an ID that could never be stored, rather than returning undefined. Existing rows that predate these rules remain readable and deletable.
The types now match these rules: _id is a string throughout, and MergePatch<T> represents patches, including null deleting an optional field.
Storage and maintenance
The retry logic had retries. A failing commit could make up to 81 create attempts. There is now one retry layer: at most three creates and one readback.
A commit uses one storage write: creating the next log/<seq> object if absent. Separate content/<sha>.json objects and index markers are no longer written.
Log cleanup uses a sequence window rather than timed mark-and-sweep. Log object counts stay bounded, and replaced snapshots are reclaimed at the rate folds create them.
The R2-over-S3 maintenance failure came from weak ETags on compressed JSON responses. Those ETags never matched If-Match, so compare-and-swap operations failed and the log accumulated. This is fixed for both r2Storage and s3Storage pointed at R2.
Garbage collection now measures grace periods from marking rather than object age on S3, GCS, and R2. Deletion candidates are tied to the generation that marked them, and orphan snapshots are checked for obsolescence before deletion. /v1/since cursors also carry a generation, so baerly admin restore --force cannot silently skip rows in an existing stream.
Other changes
- React queries support
useQuery(cb, deps, { live: false })and expose a stablerefetch(). Superseded fetches are cancelled, and expired cursors trigger a fresh subscription bootstrap. - HTTP
count()honorslimit, matching the server SDK. - JSON
Content-Typerequirements close off CORS-simple request forgery on body routes.webRootrejects symlinks that escape its root.listen(port, { hostname })supports binding to loopback, and invalidBAERLY_MAINTENANCE_*settings fail at startup. - Both packages use npm trusted publishing from GitHub Actions with provenance attestations.
create-baerly-storagebundles the dependencies resolved by its lockfile. baerly doctor --bucketchecks that LIST preserves keys.baerly cost --jsonreports cost bands, and--versionreports the package version.LocalFsStoragepreserves case-distinct keys on macOS, fixes concurrent compare-and-swap operations incorrectly succeeding together, and works across filesystems. The--with=dockercontainer starts again.
After 0.7
The aim is to stabilize the API here. Compatible fixes can ship as 0.7.x patches.
Bigger collections remain unfinished work. Any future storage-format change will come with an explicit migration. If the current limits are already too small, baerly export --target=postgres is available.
Optional: upgrading with a coding agent
The changelog includes before-and-after code for breaking changes. This prompt points an agent at those examples and leaves deployment decisions for a person:
Upgrade @gusto/baerly-storage in this repo from 0.6.x to 0.7.0.
Install: pnpm add @gusto/baerly-storage@0.7.0
Before editing, read:
- https://raw.githubusercontent.com/Gusto/baerly-storage/v0.7.0/docs/guide/upgrading-to-0.7.md
- node_modules/@gusto/baerly-storage/dist/API.md
- The 0.7.0 section of node_modules/@gusto/baerly-storage/dist/CHANGELOG.md
The shipped .d.ts files take precedence over prose.
Run the typecheck. Use the changelog's before-and-after examples to fix errors.
Replace Conflict checks according to intent: WriteConflict can be retried with
backoff; AlreadyExists cannot. Do not collapse them into the same handler.
Do not swallow or blindly retry CapacityExceeded, AlreadyExists, or
AmbiguousCommit. Preserve their recovery behavior.
Convert non-JSON values explicitly at the write site. Do not use a
JSON.parse(JSON.stringify(...)) wrapper or casts to bypass validation or the
new _id and MergePatch types.
Leave deployment config, secrets, and environment variables unchanged. Report
required operator changes, including Node 26, the Workers maintenance profile,
JWT expiry, and Workers Free with S3 over HTTP.
If this is a mixed deployment or rollback to 0.6.x is possible, stop before
rollout changes and ask about the index-marker migration.
Run the typecheck and tests. Summarize changes by upgrade-guide section and
list remaining operator work.
Changelog · Upgrade guide · npm · Docs