Object storage¶
nilo_s3 reads and writes objects in an S3-compatible bucket, where the bucket is a type your handler asks for and the key is ordinary data.
Reference: nilo_s3 · Design: Object storage
nilo_s3 works with S3, MinIO, R2, Backblaze and anything else that speaks the same API. A bucket is a type, and a key is not (ADR 059). The bucket's type carries its name as a default, so a handler asks for the bucket by type, the same way it asks for a database; a program whose bucket name is configuration opens it with openAs. The key is data, the same way a path param is.
It is a Service: it borrows the event loop and holds a named destination (an endpoint, a region, credentials). It implements SigV4 and S3's semantics and nothing else. The HTTP underneath is nilo_fetch, which makes this the only module that imports a Fitting (ADR 058, ADR 063).
const s3 = @import("nilo_s3");
and in build.zig, beside nilo_http:
.{ .name = "nilo_s3", .module = nilo.module("nilo_s3") },
A complete example¶
const s3 = @import("nilo_s3");
const Avatars = s3.Bucket("avatars", .{ .max_bytes = 2 << 20 });
fn avatar(avatars: *Avatars, c: *nilo.Ctx, key: nilo.Str) !void {
const object = try avatars.get(c, key.view());
return c.send(200, object.content_type.view(), object.bytes.view());
}
and at startup:
var store = try s3.open(gpa, .{
.endpoint = "https://s3.ap-southeast-1.amazonaws.com",
.region = "ap-southeast-1",
.credentials = .{ .static = .{
.access_key_id = settings.aws_key,
.secret_access_key = settings.aws_secret,
} },
});
defer store.deinit();
var avatars = try Avatars.open(&store);
defer avatars.deinit();
try app.provide(&avatars);
A bucket named by configuration is opened under that name and stays the same type, so one binary serves every deployment:
var durable = Durable.openAs(&store, settings.durable_bucket) catch |err| switch (err) {
error.BadBucketName => fatal(Durable.nameProblem(settings.durable_bucket).?),
else => |e| return e,
};
The name is checked by the rules the compiler applies to a declared one, copied into the bucket, and used by every log line and presignPost. open still opens the declared name.
One Store, many Buckets. The Store holds what changes between a laptop and production: the endpoint, the credentials, the signing key derived from them, and one connection pool. A Bucket holds a name and the options that belong to the bucket itself. Two buckets over one Store are two types, two services a handler can name, and one shared pool.
open does not connect to anything. A Service that needs the loop is finished when the loop exists (ADR 037), so the first credential fetch and the first connection happen inside listen(), before any connection is accepted. A bucket used before that returns error.Failed, with the reason in the log.
c is a Scope: the *Ctx, or a nilo.Run for work outside a request.
Reading objects¶
| Call | |
|---|---|
bucket.get(c, key) |
Object: bytes, content_type, etag, len, all Str in the Scope, from one allocation |
bucket.getRange(c, key, .{ .from = 0, .to = 1023 }) |
the same, for a slice. to is inclusive, the way HTTP counts. object.len is the slice and object.total the whole object's size |
bucket.getIf(c, key, etag) |
Conditional: .unmodified or .{ .object = … }. A 304 is a success, so it is a union rather than an error |
bucket.head(c, key) |
Meta: len, content_type, etag, and no bytes |
bucket.stream(c, key, &reading) |
the object left on the socket: below |
bucket.list(c, .{ .prefix, .max_keys, .cursor }) |
Page: objects and next, one page of keys and where the next page starts. Below |
max_bytes is checked against content-length before any byte is read, so an object over the limit costs one round trip instead of a download, and comes back as error.TooLarge. The limit is the largest thing a bounded get will ever put in a request arena. That is why it is part of the type: it is a fact about how much the program is prepared to hold.
getIf is for an endpoint that forwards an ETag. The browser's If-None-Match becomes the bucket's, and .unmodified becomes a 304 with no body moved at either end.
Listing objects¶
var cursor: ?[]const u8 = null;
while (true) {
const page = try files.list(c, .{ .prefix = "exports/2026/", .max_keys = 200, .cursor = cursor });
for (page.objects) |o| {
// o.key, o.size, o.etag, o.last_modified — every text a Str in the Scope
}
cursor = (page.next orelse break).view();
}
list is the only call here that asks about the bucket rather than one key, and it is bounded in three ways on purpose (ADR 058):
- A page holds at most
max_keysobjects, and at most 1,000, which is S3's own limit. Asking for more returnserror.Rejectedinstead of a page that is silently capped, so a loop sized by what it asked for never gets less. - The response body is read into the Scope up to a limit worked out from
max_keysand the bucket'skey_max. A server that answers with more than was asked for returnserror.TooLargeinstead of filling the arena. - A page marked truncated with no usable continuation token is
error.Failed: the token is missing, empty or over 1,024 bytes. Reading it as the last page would end a backup or a cleanup loop as though the bucket had been read to the end. - Nothing follows the cursor for you.
nextcomes back as text, the loop above is yours, and there is nolistAll. A helper that walked every page would be a call with unbounded output, which this module does not have, and it would turn a bucket into a database.
etag comes back quoted, the same way head and get return it, so it can go straight into getIf. last_modified is the server's own text (2026-09-18T10:11:12.000Z), and sql.Timestamp can parse it if you need arithmetic. The cost is two allocations for the body and the page, plus one per key and one per ETag for decoding. A key arrives percent-encoded (the request asks for it that way, so a key with an & in it is not an XML problem), and an ETag arrives with its quotes as XML entities.
Writing objects¶
| Call | |
|---|---|
bucket.put(c, key, .{ .bytes = …, .content_type = … }) |
also reads .cache_control and .content_disposition if the value has them |
bucket.putStream(c, key, .{ .reader = …, .len = …, .content_type = … }) |
from a *std.Io.Reader of a known length |
bucket.putMultipart(c, key, .{ .reader = …, .content_type = … }) |
from a *std.Io.Reader of unknown length: S3's multipart upload, the whole protocol in one call. Below |
bucket.delete(c, key) |
put takes any value with .bytes and .content_type, checked while compiling. A nilo.Upload already has that shape, so a file from a form goes straight through:
const NewAvatar = struct { image: nilo.Upload };
fn setAvatar(avatars: *Avatars, c: *nilo.Ctx, account: u32, incoming: nilo.Form(NewAvatar)) !nilo.Status(201, void) {
var key: [32]u8 = undefined;
try avatars.put(c, try std.fmt.bufPrint(&key, "{d}.png", .{account}), incoming.value.image);
return .{};
}
Choose the key yourself, and do not use image.filename for it: that is whatever the browser sent, ../../etc/passwd included. nilo_s3 encodes the key into a URL, once. Deciding what an object is called is the application's job.
putStream sends a length, never a chunked body, because S3 answers 411 to a body whose length it was not told. The length is a required field rather than an optional one, so "I do not know the length" is a compile error here instead of an S3 status code. An upload whose size is unknown before it starts is putMultipart's.
An upload of unknown size¶
putMultipart reads a reader to its end and makes one object of it, with S3's multipart upload underneath and none of the protocol in your hands:
const s3 = @import("nilo_s3");
const Backups = s3.Bucket("backups", .{});
fn archive(backups: *Backups, c: *nilo.Ctx, source: *std.Io.Reader) !void {
try backups.putMultipart(c, "dump.tar.zst", .{
.reader = source,
.content_type = "application/zstd",
});
return c.send(201, "text/plain; charset=utf-8", "stored");
}
The reader is read in parts of .part_bytes (8 MiB unless the source says otherwise; S3 refuses less than 5 MiB for any part but the last, so a smaller .part_bytes is error.Rejected before a byte moves). Each part goes up as its own PUT, and a completion document seals them into one object. A source that ends inside the first part becomes a plain put: one round trip instead of three, and the ETag stays the content's own MD5 rather than a multipart digest, which matters if you store objects by hash. Each part and the completion run under the source's optional .timeout_ms (no whole-call limit unless it names one) and the Store's stall_ms bound on silence, the same terms putStream gives its one body; .cache_control and .content_disposition are read off the source if it has them. Three things the call does that are easy to get wrong by hand:
- The completion's 200 is not believed on its own. S3 can answer a
CompleteMultipartUploadwith 200 and an error in the body, so the body is read and has to say so too; a 200 that does not iserror.Failed, with the reason in the log. - A failure after the initiate aborts the upload on the way out. Parked parts are paid-for bytes that no
listshows and nodeleteof the key removes; a bucket with no lifecycle rule keeps them forever. - The part count is bounded by S3's own ceiling. At 10,000 parts the upload has outgrown its
.part_bytes, and the call says so (error.Rejected, with the fix named in the log) rather than letting the server refuse part 10,001. For a reader of unknown length that moment can only arrive on the way, after those parts went up; only the part floor is checkable before any byte moves.
What it costs in the Scope: one buffer of .part_bytes, one copy of each part's ETag, and the completion document. The call holds one stream share for its whole life, the same bound stream and putStream honour, so uploads that take minutes cannot crowd out the quick calls. A part is bytes in hand, so it goes over the pooled connections and a connection the server reaped while it idled retries the way every other call here does.
A body whose size is known stays putStream's: one request, no protocol, no part floor.
Copying inside the store¶
copy makes an object at another key from one already in the bucket, and compose makes one from several, in order, without a byte passing through your server:
const s3 = @import("nilo_s3");
const Items = s3.Bucket("items", .{});
fn keep(items: *Items, c: *nilo.Ctx, staged: []const u8, pieces: []const []const u8) !void {
// One staged object to its final key: type and headers come with it.
try items.copy(c, staged, "items/whole.bin");
// Several, joined in order: the new object says what it is.
try items.compose(c, "items/joined.bin", pieces, .{ .content_type = "application/octet-stream" });
return c.send(201, "text/plain; charset=utf-8", "kept");
}
copy keeps the source's content type and headers. compose is a multipart upload whose parts are copies, so it starts with no object to keep them from, and takes .content_type (and optionally .cache_control and .content_disposition) the way putMultipart does. S3's rules hold: one copy up to 5 GiB; a join of 1 to 10,000 parts, each at most 5 GiB and all but the last at least 5 MiB.
- A copy's 200 is not believed on its own. S3 can answer one with 200 and an error in the body, so the body is read and has to say it copied; a part copy has to name its ETag. Anything else is
error.Failed, with the reason in the log. - A join that fails is aborted, and the target is left as it was. The completion is the only step that makes an object, and it is never sent after a failure.
- The store works while the call waits, and only the Store's
stall_msbounds it. A copy has no whole-call limit (the Store'stimeout_msdoes not apply), because cutting a copy that is working can leave the store finishing what you were told failed. AWS says a copy's 200 can arrive before the copy is complete, with an error in the body if it then fails, and documents no keep-alive while it waits; if your store keeps a large copy's connection quiet, give the Store astall_mslonger than that.
Streaming a large object¶
get puts the object in the request arena, which is right for an avatar and wrong for a video. stream leaves it on the socket:
const s3 = @import("nilo_s3");
const Videos = s3.Bucket("videos", .{});
fn watch(videos: *Videos, c: *nilo.Ctx, key: nilo.Str) !void {
var reading: Videos.Reading = .idle;
defer reading.close();
try videos.stream(c, key.view(), &reading);
var body = try c.streamWith(200, reading.content_type, .{ .length = reading.len });
_ = try reading.pipe(&body.writer);
try body.finish();
}
After stream returns, Reading carries len, total, content_type and etag. pipe(w) then moves the bytes into any *std.Io.Writer (a response, a file), and close() gives the connection, the permit and the stream slot back.
A stream is not cut at timeout_ms. That is the budget for a call that moves a bounded body, and a video going to a slow browser has no honest bound, so watch() above ends when the object does, or when no byte has moved for stall_ms (30 s), which is error.TimedOut. To put a ceiling on one, set it before the call: var reading: Videos.Reading = .{ .timeout_ms = 600_000 };. A streamed put takes the same from its source, .timeout_ms = 600_000 beside .reader, .len and .content_type. A stream also takes one of max_streams slots (half of max_in_flight unless you say), so a few slow viewers leave the rest of the permits to the short calls.
content_type and etag are borrowed and valid only until pipe. They point into the connection's read buffer, and the first byte of the body overwrites it. Set the response headers from them first, and copy them if you need them afterwards. A Reading must not be copied once started, for the same reason a fetch.Exchange must not: it holds one.
.length = reading.len gives the browser a Content-Length to draw a progress bar against and lets it resume with a Range (Streaming). To serve that Range from an object of any size, set .range on the Reading before stream: var reading: Videos.Reading = .{ .range = .{ .from = 5_000_000, .to = 5_999_999 } }; moves only those bytes, len is how many and total is the whole object's size, for the Content-Range your answer sends. max_bytes does not apply, a reversed range is error.Rejected, and an answer that is not a 206 is error.Failed rather than the whole object taken for a slice.
There is no buffer to declare. Until 0.5, stream took one, and the guide said a bigger buffer meant fewer trips into the connection. In fact the bytes go from the connection's own read buffer to your writer and never passed through it; bench/result/s3.md had already measured going from 64 KB to 8 KB as a one-byte difference. How much one read brings in is set by the client's read_buffer_size (ADR 186).
Presigned URLs and upload forms¶
These two calls let a browser read or upload an object without the bytes passing through your server. Neither opens a socket: each only computes a signature.
| Call | |
|---|---|
bucket.presign(c, key, seconds) |
Presigned: url and expires_at. A link to download one object |
bucket.presignPut(c, key, seconds) |
the same, for a PUT: a link a process uploads one object to |
bucket.presignPost(c, key, .{ .seconds = 900 }) |
Posted: url, fields and expires_at. A form for uploading one |
A PUT link is for a process the server checks up on; a browser gets the form. The method is inside the signature, so presign's URL and presignPut's are not interchangeable: each is a 403 under the other's verb. And a plain PUT has no size condition (SigV4 has nowhere to carry one), so a server handing out PUT links verifies what arrived (a head for the size, the content hash if it stores by one) before recording it. A browser upload belongs on presignPost, whose policy always carries the bucket's ceiling (ADR 112).
expires_at is the real expiry. A URL signed with temporary credentials stops working when they expire, whatever X-Amz-Expires says. So the reported lifetime is the smallest of what you asked for, the bucket's presign_max, and what the credentials have left. A caller that stores it in a database stores the right value.
A presigned POST is a form rather than a link. url is the bucket, and fields go into the form in the order they come back, with the file input last, because S3 ignores anything after the file part. The first field is bucket, because Garage rejects the form without it and AWS ignores it.
<form action="{url}" method="post" enctype="multipart/form-data">
<!-- one hidden input per field, in order -->
<input type="file" name="file"> <!-- last -->
</form>
s3.Post |
Default | |
|---|---|---|
seconds |
none | clamped the same three ways presign's are |
content_type |
null |
an eq condition on $Content-Type. Null lets the browser send what it likes |
max_bytes |
the bucket's | clamped to it, and defaulted to it, so this never hands out a form with no size limit |
prefix |
false |
key is the start of a key rather than the whole of one, so the browser picks the filename |
The POST policy lives in nilo rather than in your application because of one detail of SigV4. It is signed with the key nilo derives once a day (ADR 060), and a second implementation outside nilo means two places that have to agree about the daily rotation. They disagree at 00:00 UTC, and the symptom is uploads failing with a 403 that explains nothing.
Store options¶
Passed to s3.open:
| Field | Default | |
|---|---|---|
endpoint |
none | https://host[:port] or http://host[:port], no path |
public_endpoint |
null |
the endpoint a browser reaches, when it is not the one this process connects to: below |
region |
us-east-1 |
|
credentials |
none | .static or .fetch: below |
max_in_flight |
32 | calls at once, across the process. An HTTPS connection allocates 59,151 bytes (12 KB resident after a small answer, 45 KB after a large one), so this times that is the store's memory ceiling |
timeout_ms |
30,000 | one call, end to end, for get, head, list, put and delete; stream and putStream are not cut by it |
stall_ms |
30,000 | how long a stream or putStream may move no bytes before it fails with error.TimedOut: a slow transfer that keeps moving is fine, a quiet one is not |
max_streams |
half of max_in_flight |
how many stream and putStream calls may be open at once, so that slow downloads cannot hold every permit and queue get, head and list behind them |
fetch_timeout_ms |
10,000 | how long a credential fetch may take: below |
max_drain |
64 KiB | how much of a rejected response body is worth reading to keep the connection |
refresh_margin_s |
300 | how long before expiry temporary credentials are replaced |
retry |
null | try Throttled and Unavailable again: below |
The endpoint's scheme decides whether payloads are hashed: UNSIGNED-PAYLOAD over TLS, a real SHA-256 over plain HTTP. There is nothing to configure (ADR 060). This means the plain-HTTP numbers in bench/result/s3.md include a hash over every body that the HTTPS numbers do not, and the HTTPS numbers include a TLS record layer that the plain-HTTP ones do not.
An endpoint that is not scheme://host[:port], or whose host and port run past 255 bytes, returns error.BadEndpoint from open, and a region longer than a credential scope can hold, or holding a ,, /, space or control byte, returns error.BadRegion. A max_streams larger than max_in_flight returns error.BadStreams. Static credentials that could never sign return error.BadCredentials: an empty key id or secret, a key id with those same bytes in it, or an expires_at already past. open copies a static pair, so a config buffer may be reused afterwards.
A public endpoint for the browser¶
Set public_endpoint when the browser reaches the store at a different address than your process does. A process might reach the store on a Docker network or a Tailscale address that a browser holding a presigned URL cannot reach. public_endpoint is the host the browser uses, and it appears in every presigned URL and every POST form, signed as that host. Rewriting the URL afterwards cannot do this job: the host is part of the signature, and a presigned GET with a rewritten host fails with a 403 that looks like a signing bug (ADR 177). Every call that connects (get, put, head, delete) still connects to and signs for endpoint.
var store = try s3.open(gpa, .{
.endpoint = "http://garage:3900",
.public_endpoint = "https://files.example.com",
.credentials = .{ .static = .{ .access_key_id = cfg.s3_key, .secret_access_key = cfg.s3_secret } },
});
Bucket options¶
The second argument to s3.Bucket. Every field describes the bucket itself; anything that changes between development and production belongs on the Store.
| Field | Default | |
|---|---|---|
max_bytes |
8 MiB | the largest object a bounded get will hold |
style |
.virtual |
https://avatars.s3…/key. .path (https://s3…/avatars/key) is for MinIO and anything on a bare host |
sse |
null |
.aes256 or .aws_kms, sent as the header S3 already understands |
presign_max |
3600 | the longest lifetime a presigned URL from this bucket may have |
key_max |
512 | the longest key. Comptime because it sizes a stack buffer at 3× this, and stack is per connection; S3's own limit is 1,024 |
session_token_max |
0 | room for a session token beside a signature. Zero is right for static credentials and costs nothing; an STS source sets 2048 and pays for it per connection |
A bucket name that could never work stops the build with a message. That covers an empty name, or a name that is not a legal DNS label under .virtual, and the same rules run in openAs on a name read at run time, which answers error.BadBucketName. A credential written into the options also stops the build: secret, access_key and similar names are rejected, because a bucket's type is compiled into the binary and ships with it. Credentials belong on the Store, where a Config can read them.
Credentials¶
.credentials = .{ .static = .{ .access_key_id = "…", .secret_access_key = "…" } },
is a key pair for the life of the process. Temporary credentials (IRSA, IMDS, anything STS hands out) are a function:
.credentials = .{ .fetch = fromIrsa }, // fn (gpa: std.mem.Allocator, io: std.Io) anyerror!s3.Credentials
It is called once at startup, and again when the credentials in hand are within refresh_margin_s of expiring. It is called lazily, by the request that notices: there is no background task. Because the refresh happens five minutes early, the request that pays for it is never one that would otherwise have failed. If the refresh fails, the credentials in hand keep signing until they actually expire, and the next try is five seconds later; one request refreshes while the others keep signing. Credentials that live less than the margin are refreshed at half their life. The Store copies what the function returns, so its strings only have to outlive the call, and the Store cancels the function if it takes longer than fetch_timeout_ms (ten seconds). A timeout counts as a failed fetch: the credentials in hand keep signing until they expire, and past that the requests that wait get error.TimedOut from the bucket, with CredentialsTimedOut in the log. Cancellation is cooperative and lands at the function's next Io call, so pass the io you are given to whatever you call and return what it returns. A Credentials carries session_token and expires_at for this case, and the bucket's session_token_max has to be raised from zero to make room for the token.
Errors¶
There are seven errors, because a handler would do something different about each:
| Error | Answer | |
|---|---|---|
error.NotFound |
no object at that key (a bucket that does not exist is Rejected) |
404. The only one with a default, because its meaning does not change with the request |
error.TooLarge |
the object is over max_bytes, rejected before any byte was read |
yours |
error.Throttled |
S3 is shedding load: SlowDown, or a 503 |
a default image and a 200, or a 503; only the handler knows |
error.Unavailable |
S3 answered 5xx. Separate from Throttled because backing off helps with one and not the other |
502 or 503 |
error.TimedOut |
this call's deadline passed | 504 |
error.Rejected |
S3 rejected the request: credentials, signature, permissions, or a bucket that does not exist. Or nilo refused it before sending: an empty key, which would address the bucket rather than an object, or a header value with a control byte, which would split the request | 500, not 403. Telling the caller they are not allowed, when the real problem is that the server's credentials are wrong, is a lie in the place where it costs the most debugging |
error.Failed |
everything else, including a response nilo could not make sense of | 502 |
Retrying a throttled call¶
By default a Throttled or an Unavailable reaches your handler, where an AWS SDK would have tried three times. Say .retry on the Store and the calls whose bytes are in hand (get, getRange, getIf, put, head, list, delete, copy) go round again, each try signed afresh, with nilo_fetch's mechanism (the fetch guide, ADR 271):
var store = try s3.Store.open(gpa, .{
.endpoint = cfg.s3_endpoint,
.credentials = .{ .static = cfg.s3_credentials },
.retry = .{ .times = 3, .backoff = .{ .exponential = .{ .from_ms = 100, .to_ms = 2_000, .jitter = .full } } },
});
times, backoff and budget are what is read here, and the budget is the Store's, shared by every bucket over it, so S3 shedding load costs it no more than that share above the calls it was given. The wait holds no permit, and it never outlives the route's deadline. stream, putStream and the multipart upload are not retried: a reader is spent by the first try, so a failed upload comes back to you to start again from a source you can read twice. Retry-After is not read, because S3's answers reach this module as the two errors.
S3's own error code and message are logged, not sent to the client. A skewed clock (RequestTimeTooSkewed) is read out of the response body and stated plainly in the log, because it is the one S3 error whose fix is on your machine.
What it costs¶
Per request, nothing beyond the call itself. Signing is one SHA-256 over the canonical request, one HMAC, and the hex encoding, because the derived key changes once a day and is kept for the day (ADR 060). The canonical request is never built as bytes; it is written straight into the hash, which is why the module has no per-request buffer for it.
Per idle connection, what a handler's stack adds: the encoded key at 3 × key_max, and the stack depth nilo_fetch drives the fiber to. bench/result/s3.md measures all of it against the same seven routes written in Go and Rust, and explains which route was the expensive one and why it was not the one anybody expected.
What it will not do¶
A list that follows its own cursor is not built: one bounded page and the cursor to the next is the call, and the loop is yours. list, multipart upload and COPY were each refused as a document format and let in one caller at a time (ADR 058): a fixed, flat document with a handful of interesting names is a scan rather than a parser.
Arbitrary x-amz-meta-* headers are rejected for a performance reason that a measurement could change: a fixed header set is what keeps building SignedHeaders a simple walk instead of a sort on every request.
Testing¶
zig build test-s3 runs the module's tests against a fake S3 on a loopback socket that checks every signature, with no container and no network. With S3_ENDPOINT and the related variables set, it runs against a real one. The quickest one to develop against is SeaweedFS in a container, which is what CI runs, with bench/s3_setup.py creating the bucket and objects the tests and the benchmark need:
docker run -d --name seaweedfs -p 9100:8333 \
-e AWS_ACCESS_KEY_ID=niloadmin -e AWS_SECRET_ACCESS_KEY=nilosecret123 \
chrislusf/seaweedfs:4.47 server -dir=/data -s3 -s3.port=8333
python3 bench/s3_setup.py
Then .endpoint = "http://127.0.0.1:9100" and .style = .path.
A handler that takes a *Avatars is an ordinary function. Test the parts that do not need the bucket (which key a request maps to, what a NotFound becomes) and leave the bucket calls to the module's own test suite.
See also¶
- The reference: the full list of calls.
- Calling somebody else's API: the client underneath, and the
ExchangeaReadingis built on. - Forms: the
Uploadthatputaccepts as it is. - ADR 059: why the name is a compiled-in default and the key is not.