karu

How Karu reads

  • What happens between asking for a byte range and getting a filled buffer back.

Karu is a byte-range reader. Each read names an object, an offset, a length and a destination buffer. Karu retrieves the bytes from a local file, an HTTP server or a cloud object store and reports a completion for every read. This page follows a single read from its description to its completion and explains the design decisions at each stage.

One read, seen from end to end

The example reads 4 KiB starting 1 MiB into an object on S3. Its four steps show the request the caller fills in, the transfer the planner makes of it, the HTTP exchange Karu sends and checks, and the completion it returns. Local files follow the same steps, with a pread in place of the HTTP exchange.

Follow one read

Click a step, or use the arrow keys.

karu_req read = {
    .locator = scene,      // karu_resolve("s3://bucket/scene.tif")
    .offset  = 1048576,
    .length  = 4096,
    .buffer  = buf,
    .tag     = (void*)7,
};

The caller describes the read once, in a karu_req. The tag belongs to the caller. Karu returns it unchanged, so each completion can be matched to its read regardless of arrival order.

Karu knows where the bytes are stored, which range is requested and which buffer receives it. It does not know what the bytes represent, whether an image tile, a Parquet row group or a compressed frame. The rest of the design follows from this separation. Because Karu never interprets the bytes, it can reorder reads, merge neighbouring reads into one request and retry them.

Internally, the read is kept separate from the network request that serves it. The planner turns reads into transfers, one local read or one HTTP request each. Every read becomes a part of some transfer, and every part finishes as its own completion. Three reads can share one request and still produce three completions, each with its own buffer and tag. If that shared request fails, all three report the failure.

What Karu does and what it leaves to the caller

Karu only reads. It resolves addresses, reports sizes and reads ranges from local files, plain HTTP, Amazon S3 and compatible stores, Google Cloud Storage, Azure Blob and Data Lake Storage, Hugging Face and Source Cooperative. It can also download large objects in parallel. It never writes, deletes or lists remote objects, it does not parse formats, and it does not cache object data.

A read is a location, not a cursor

Karu reads the way pread does, the classic positional read of POSIX. Each read carries its own object, offset, length and destination, and nothing is stored between reads, so there is no file position to seek or to protect with a lock.

An ordinary file handle keeps a cursor. Reading moves it forward and seeking moves it elsewhere, so two threads sharing one handle step on each other. pread takes the offset as an argument instead and never moves the cursor, and Karu applies that model to every backend, remote objects included. That is what stateless means here. No read changes anything another read can see, so the engine can run reads in any order, or all at once.

Cursor reads compared with positional reads Cursor reads share and move one position while positional reads carry independent offsets. CURSOR MODEL one mutable position shared by later reads read advances the cursor POSITIONAL MODEL read Aread B offset 118offset 412
With a cursor, every read depends on the one before it. With positions, reads A and B can run in either order or at the same time.

A local file and a remote object differ more than the API suggests. A file descriptor is a kernel handle, and pread copies from the page cache in microseconds. A remote object has no open handle, and every read is a network exchange that may need a DNS lookup, a TLS connection, a signature and a fresh response. A 4 KiB read can easily wait 50 or 100 ms, nearly all of it in round trips. That is why Karu works so hard on request count, concurrency and connection reuse.

Ranges and windows

Drag the sliders. The object is 64 KiB.

Requested interval[16,384, 20,480)
In the objectthe same, no window
Header Karu sendsRange: bytes=16384-20479
What happens206 with Content-Range: bytes 16384-20479/65536

Karu thinks of a read as the half-open interval [offset, offset + length). HTTP names the last byte instead, so Karu sends bytes=first-last with last = first + length - 1. A read past the end of the object still returns the bytes that exist. The completion reports that prefix in got, with KARU_ERR_RANGE for the rest.

A locator can also be a window into a larger object, such as one file inside an uncompressed archive (/vsisubfile/, or #bytes= on a URI). Offset 0 is then the first byte of the window. Karu adds the window start before building the request, and a read that leaves the window fails right away, without a request.

How an HTTP Range request works

A normal GET asks for the whole resource. A Range request adds one header that names the requested bytes. A server that supports it answers 206 Partial Content with a Content-Range header repeating the interval and, usually, the total size. A 200 means the server ignored the range and is sending the whole object. A 416 means the range starts past the end.

Resolving a locator with karu_resolve touches neither the network nor credentials. It only works out the backend, the canonical path, the bucket or container, the key and the window. Configuration rules, merging and credential reuse are all keyed on the canonical path, so s3://bucket/key and /vsis3/bucket/key behave the same.

Reads are submitted in batches

Most of the time taken by a remote read is spent waiting for the server. Reads submitted one at a time pay that latency once each. Reads submitted together overlap their waits, and Karu can identify reads that lie close together in the same object.

Sequential reads compared with a concurrent batchFour sequential reads wait one after another while four batched reads overlap and finish in different order. ONE AT A TIMEONE BATCHtime read Aread Bread Cread D read Aread Bread Cread D completions arrive when each read finishes
The four waits overlap, and the reads finish in whatever order the servers answer. The tag identifies the read behind each completion.
karu_batch* batch = NULL;
karu_client_submit(client, reads, count, &batch);

karu_done done;
while (karu_batch_next(batch, &done, -1) == KARU_OK)
    use(done.tag, done.status, done.buffer, done.got);

karu_batch_free(batch);

karu_client_submit copies the request descriptions and returns immediately. karu_batch_next returns one completion at a time, in the order the reads finish rather than the order of submission, and several threads can drain the same batch. When all results are needed together, karu_client_fetch waits for the whole batch.

Two kinds of mistakes are caught at different times. A malformed request, such as a zero length, no locator or a line break in an ETag, makes the whole submit fail with KARU_ERR_INVALID, and no batch is created. A range that leaves its window fails only that read, as an immediate completion, while the rest of the batch carries on.

Buffers

Each destination belongs to one read, even when that read shares a request with others. A buffer supplied by the caller must remain valid until the batch is freed. When the destination is NULL, Karu allocates the buffer and returns it in the completion, and the caller releases it with karu_free.

The lifetime of a destination bufferThe caller creates or requests a buffer, Karu writes while the batch is active, the completion makes the valid prefix readable, and ownership ends when the buffer and batch are released. Describeprovide a bufferor ask Karu to allocate Batch activebuffer stays aliveworkers may write Completionstatus and got arrivevalid prefix is readable Releasefree the batchrelease owned memory Only the first got bytes may be read. Memory beyond that prefix is unspecified.
Even when reads share a request, each completion returns the buffer of its own read.

Two statuses, two meanings

karu_batch_next returnsMeaning
KARU_OKOne completion is ready. Its own status says whether that read worked.
KARU_TIMEOUTThe wait ran out. Nothing is lost; call it again.
KARU_ENDEvery read in the batch has completed.

Freeing a batch with karu_batch_free cancels its pending work, including requests already on the network, and waits until no worker still touches its buffers. Do not call it while another thread is inside karu_batch_next on the same batch.

Fewer requests can move the same useful bytes

Before anything is read, the planner checks each request, turns window offsets into object offsets, sorts reads by object and offset, and walks through them once, joining neighbours while the trade still makes sense.

Four rules for merging

Default values, holes not to scale.

Gap 1 MiB

KARU_COALESCE_GAP

The next read joins the request when the hole before it is at most 1 MiB.

READSREQUESTSABC512 KiB2 MiBAdroppedBGET 1CGET 2hole 512 KiB≤ 1 MiB, joinshole 2 MiB> 1 MiB, new request

The gap and the ratio decide which ranges merge, and the span and the parts decide how big one request gets. The planner checks all four for each next read. One failed rule closes the current request, and that read starts the next one. The values shown are the defaults, and the configuration reference lists the options.

A batch can change all four with karu_client_submit_with, or SubmitOptions in C++. A gap of 0 turns merging off. Merging pays when round trips are expensive and the link is fast; on a slow link a smaller gap can be quicker, so the bytes fetched matter as much as the request count.

Local files are different. A pread gains nothing from reading through a hole, so local reads only merge when they overlap or touch. Reads with different if_match values never share a request, even when their ranges overlap, because they are different conditions on the object.

Splitting the answer back up

A merged remote response is never stored as a whole. As each chunk streams in, Karu copies it straight into every buffer it overlaps and discards the bytes that fall in the holes. A merged local read is done into a scratch buffer first and then copied out. In both cases each read completes on its own, and overlapping reads are allowed. Both buffers get the shared bytes, and both lengths count as useful when the ratio is checked.

Local and remote reads share a contract

With the plan ready, local transfers go to four file workers. Remote ones stop first at one of four credential workers, which loads or refreshes credentials without holding up the network, and then join the HTTP queue that the I/O threads drain. Plain HTTP and Hugging Face skip the credential step.

Local and remote routes through the Karu engineThe plan splits into file workers for local reads and credential workers and the I/O threads for remote reads. Both routes produce completions. Transfer planlocal and remote work LOCAL PATHFile workerspositional pread REMOTE PATHCredential workersresolve without blocking network progressI/O event loopslibcurl multi and handle pool Completionsone result per original read
Disk reads and credential lookups, which can block, run on workers. The I/O threads drive the network and sign each request just before sending it.

A large batch does not create a large number of threads or sockets. Transfers beyond KARU_CONCURRENCY, 64 by default, wait in the queue, and each finished transfer lets the next one start. A batch may describe a million reads, but only 64 are on the network at any moment, and the caller drains completions at its own pace.

KARU_IO_THREADS sets how many I/O threads split that limit, four by default with 16 transfers each, every one with its own libcurl multi handle and connections. Karu fills them in order, and a thread only takes queued work when no lower thread has room. A small batch therefore runs on the first thread again and again, on the connections it already opened. More threads help when TLS, signing or copying keeps one core busy. With several worker processes, compare 1 and 4 on the real workload, including decoding.

A remote read becomes an HTTP exchange

For each remote transfer an I/O thread finds or opens a connection, sends one prepared request, and streams the response into Karu.

Before the first byte

The host name goes through DNS to get an address. TCP opens a connection, and TLS encrypts it and checks the server's certificate. Only then can the HTTP request go out. A cold connection pays several round trips before any data moves, which for a small range can take longer than the transfer itself.

The setup required before an HTTPS range request DNS resolves the host, TCP creates a stream, TLS secures it, and HTTP carries the range request. DNSfind address TCPopen stream TLSsecure stream HTTPsend range Bytesreceive body a live connection can serve later requests new connections repeat setup and add round trips before useful data moves
A small range can spend longer setting up the connection than receiving its body, which is why Karu keeps connections open.

On Linux and macOS, batch reads resolve names on a separate thread, off the I/O threads, keep each answer for a minute, and rotate new connections across the addresses a host returns. Elsewhere, and for requests through a proxy, libcurl's own resolver and cache do the job.

The request

Karu always sends GET, with no body. The headers carry the host, the range, an If-Match when the read sets one, and the provider's authentication. Every backend (S3, GCS, Azure, Source, Hugging Face, plain HTTP) produces the same prepared request, made of a URL, headers, a closed range and a few options. The transport sends it without knowing how it was signed.

Each attempt is built just before it is sent, from the configuration for the object's canonical path and the credentials the transfer already holds. Credentials are loaded once per transfer and fetched again only if the service says they expired. An S3 region correction also takes effect on the next attempt.

Keeping connections alive

Each I/O thread keeps its own connections and a pool of reusable easy handles. A share handle lets all threads reuse TLS sessions and DNS answers, so a reconnect skips most of the handshake. The multi handle is the event loop. It waits for sockets that are ready, advances only those transfers, collects the finished ones and starts queued work up to the limit. Hundreds of waiting requests cost almost nothing.

Karu uses HTTP/1.1 by default, one response per connection at a time. KARU_HTTP_VERSION can ask for HTTP/2, which carries many requests over one connection. That saves setup, but then every request shares that one connection's bandwidth.

Draining instead of hanging up

Stopping in the middle of a response body leaves the connection unusable, because the next response would begin at an unknown point. When up to 256 KiB of unwanted data remains, Karu reads and discards it so the connection can go back to the pool. When more remains, it aborts through the write callback and opens a new connection later.

A successful response must prove what it contains

A request that finishes without an error has not proved anything yet. Karu compares what came back with the range it asked for.

What the server sent back

A read of 4,096 bytes at 1,048,576. Pick an answer.

HTTP/1.1 206 Partial Content
Content-Range: bytes 1048576-1052671/4194304
body: 4,096 bytes
statusrangelength

KaruKARU_OK got 4,096

A 206 must carry a Content-Range that starts at the requested first byte and ends at the requested last byte, or at the last byte of a shorter object. It may never reach past what was asked. The body length is checked on its own, so a correct header over a cut-off body still fails.

A 200 is accepted only when skipping to the offset is cheap, at most KARU_RANGE_FALLBACK_LIMIT, 8 MiB, of discarded data. Beyond that Karu refuses rather than turn a small read into a large download.

GCS can decompress gzip objects on the fly and ignore Range while doing it. For gs:// paths Karu sends Accept-Encoding: gzip to get the stored bytes, and it rejects any response that says it was transformed.

Sizes, both ends, whole objects

karu_client_size and karu_client_stat learn a remote object's size with a one-byte GET of byte 0, reading the total from Content-Range, so the probe is signed like a real read and must get a valid range back. A window already knows its size, so size sends nothing for it. stat also returns the strong ETag. An empty object answers 416 with a total of zero. Karu does not cache sizes, because only the application knows how long a size remains valid.

karu_client_read_ends fetches the start and the end of an object at the same time, for formats with a header and a footer. It sends one request for the head and one suffix range for the tail. Azure ignores suffix ranges, so there the tail waits for the head and is pinned with its ETag. When both answers carry an ETag they must match, and they must agree on the size. Like size and stat, this call runs outside the batch engine and does not count against the concurrency limit.

karu_client_download writes a whole object to a file. One read of up to 1 MiB learns the size and the ETag, then 8 MiB chunks follow, eight at a time, each pinned with that ETag. Everything goes into a temporary file next to the destination, which appears only when every chunk has landed. An existing file is replaced only when the caller requests it.

Several reads, one version

Each response can be correct while the set is inconsistent. If the object is replaced between two reads, the result mixes bytes from two versions. An ETag names one version of an object. karu_client_stat returns it. When it is passed as if_match on related reads, Karu sends If-Match with each request. If the object changed, the server answers 412 and the read fails with KARU_ERR_PRECONDITION. Karu also compares the ETag the server sends back, in case it ignored the condition.

stat is unnecessary when the version is already known. A reader with an external index, for example, can read ranges straight from it, as long as the index belongs to the same version of the data. Without if_match every response is still checked, but separate requests do not form one snapshot. ETags apply to remote objects only.

Different failures need different next steps

Some failures disappear on a second attempt, some require a different request and some are permanent. Karu classifies each failure before deciding how to proceed.

When an attempt fails

Pick a failure.

Connection timed out after 30000 milliseconds
or: Recv failure: Connection reset by peer

Karu waits and tries again. The first retry waits 200 ms plus up to as much again in random jitter, and the base doubles on each retry up to 6.4 s. A read gets up to 8 attempts, all inside one request timeout.

Karuretry then KARU_ERR_NETWORK when attempts run out, or KARU_TIMEOUT when time does

Retrying is safe because a read changes nothing. Doing it twice has the same effect as doing it once, which is what idempotent means. Karu retries timeouts, dropped connections, failed lookups, empty replies, partial transfers and a few TLS and HTTP/2 errors, plus HTTP 408, 425, 429, every 5xx, and S3's 400 RequestTimeout. It decides from libcurl's result codes and the HTTP status, plus a few error codes that S3 puts in the body, never from the wording of a message. Everything else, such as a bad path, denied access, a failed precondition or a malformed response, is returned to the caller immediately.

All attempts of a read share one deadline, KARU_REQUEST_TIMEOUT, 120 s by default, waits included. For cloud reads the clock starts when a credential worker picks the transfer up, and for plain HTTP and Hugging Face when an I/O thread does; time spent queued before that does not count. Connecting has its own 30 s limit, and a connection that moves less than 1,024 bytes per second for 60 seconds is dropped. Karu never starts a wait that would end after the deadline.

An interrupted read resumes where it stopped when Karu can pin the rest to one version, either with the caller's if_match, if it is a single strong ETag, or else with the strong ETag the server sent. Otherwise, including a wildcard or a list in if_match, the range starts over. If the saved ETag stops matching, Karu discards the partial data and starts again, unless the caller supplied the ETag, in which case the read fails.

S3 signs with Signature Version 4, which covers the method, path, headers, time, service and region. That is why the region and expired-credential cases get their own one-time correction instead of an ordinary retry. The next request has to be different, not repeated. Karu keeps only the first 4 KiB of an error body for these decisions and for the message.

Credentials are reused only where they are valid

Cloud reads need proof of identity. Karu loads it on the credential workers, away from the I/O threads, reuses it only where it is valid, and refreshes it before it runs out.

Each provider has its own sources, such as keys, profiles, helper programs, metadata services or an application callback. The configuration reference lists the order Karu tries them in for AWS, Source Cooperative, Google Cloud Storage and Azure. Hugging Face is simpler. The token comes from HF_TOKEN, or is read again from its file for every request, so a new login takes effect at once.

One credential lookup serves matching pathsThree requests under one path scope converge on one credential load and reuse the result. MATCHING PATHSbucket / imagery / abucket / imagery / bbucket / imagery / c Single flightone loader, shared resultScoped cacherefresh near expiryA different credential scope starts a different lookup
Three reads under one scope cause one lookup. A path with a different scope gets its own.

Karu caches credentials by scope, which is the provider plus where each credential option came from for that path. Two paths share credentials only when they resolve to the same scope. When many reads hit a cold scope at once, one lookup runs and the others wait for its answer, so a big batch does not start a hundred credential_process helpers or flood a metadata service.

Refreshing is lazy. In the last tenth of a credential's lifetime, between 1 and 60 seconds before it expires, the next request fetches a new one while the others for that scope wait. Keys without an expiry are read again every minute, so a rotated profile is picked up. A failed lookup is reported but not remembered, and the next request tries again.

With a custom provider the callback chooses the scope. It returns a cache_prefix covering the paths the credentials are valid for, or none to be called for every request. Before the first answer arrives, Karu only knows the exact path, so cold reads of different objects under one prefix each call the provider once.

One client, tuned from measurements

Remote reads are usually limited by latency rather than CPU. Reuse one client, submit real batches and tune only what a measurement identifies.

One client

A client owns the engine, its threads, the connection pools, the credential cache and the S3 regions it has learned. A client per read throws all of that away every time. Create one with karu_client_create, share it across threads, and keep it.

The client keeps a frozen copy of its configuration. Changing the config object afterwards does not affect it; create a new client when different settings are needed.

What to tune

OptionDefaultWhen to change it
KARU_CONCURRENCY64Raise it when the network sits idle waiting on latency. Lower it to go easier on a server or on the process.
KARU_COALESCE_*1 MiB, 64 MiB, 1,024, 16Watch fetched bytes as well as requests. A fast batch can hide wasteful merging, and a slow link may prefer a smaller gap.
KARU_IO_THREADS4Compare 1 and 4 with several worker processes.
KARU_REQUEST_TIMEOUT, KARU_MAX_ATTEMPTS120 s, 8A retry only helps if there is time left for it to finish.

Path options let one client serve many buckets with different settings. The longest matching prefix wins over a client-wide value, which wins over the environment and the default, as the configuration reference explains. The same canonical path scopes credentials, so a setting chosen for one bucket can never authorize another.

After fork

A forked child cannot use its parent's threads. Karu notices the new process on first use and builds a fresh engine with its own connections, which is what PyTorch DataLoader workers need. Submit batches in the process that drains them. A batch inherited across fork() returns KARU_ERR_INVALID in the child, and freeing it there leaves it allocated until the process exits.

C and C++

The stable boundary is the C ABI in karu.h, with opaque handles, numeric statuses, and no exceptions or C++ types across it, which keeps language bindings simple. karu.hpp wraps it for C++ with owning handles, spans, std::expected results and per-batch overrides. Both reach the same engine.

What Karu does not cache

Karu keeps connections, TLS sessions, DNS answers, credentials and bucket regions, because each serves many reads. It never caches object bytes or sizes. A data cache needs eviction, invalidation and a memory budget that depend on the workload, so it belongs in the layer that knows the data.

Measuring

Planner benchmarks should report requests, fetched bytes, requested bytes and planning time. karu_batch_get_stats counts transfers, requested and received bytes, retries and new connections; planning time has to be measured separately. Network benchmarks should keep the first cold batch apart from steady state and use a real remote endpoint, because a local server hides exactly the latency that batching and concurrency are meant to hide.