Streaming, Data Movement, and How Bytes Travel
A from-scratch guide to how data moves from one place to another — first as a set of generic, technology-agnostic ideas, then grounded in one real system: the sidecar that streams backup data to S3, using the real code in
file_store_service.go,filestore/s3.go, andproto/sidecar.proto.Read top to bottom. It goes beginner → advanced, and generic → concrete. No prior knowledge of streams, gRPC, or
io.Readerassumed.How to read it: Part I builds a mental model that applies to any system that moves data (a file copy, an HTTP upload, a Kafka consumer, a database replication feed). Part II is a single worked example that makes every abstraction concrete. If you only care about the ideas, read Part I. If you want to see them in real code, read both.
Part I — The generic model
Everything in Part I is deliberately technology-free. Substitute your own system as you read: "producer" might be a browser, a microservice, a sensor; "consumer" might be a database, a disk, a cloud bucket; the "boundary" might be a network socket, a Unix pipe, or a function call.
1. The problem, stated generically
Almost every data-movement problem is the same shape:
A producer has data. A consumer wants it. Between them sits a boundary they cannot see across directly. How do you move the data across that boundary — correctly, and without holding all of it at once?
┌────────────┐ boundary ┌────────────┐
│ PRODUCER │ ───► (a gap you ───► │ CONSUMER │
│ has data │ must cross) │ wants data │
└────────────┘ └────────────┘
The three pieces are always present:
| Piece | What it is | Examples |
|---|---|---|
| Producer | The source that has or generates bytes | a file on disk, an app in memory, a device, another service |
| Consumer | The sink that wants the bytes | a database, object storage, a socket, a screen |
| Boundary | The gap between them that has cost and can fail | a network hop, a process boundary, a disk, a language ABI |
The boundary is the whole reason this is hard. If producer and consumer were the same function on the same CPU, you'd just pass a pointer. The moment a boundary exists, four new questions appear — and the rest of this doc is answering them:
- Representation — in what form do the bytes cross? (section 2 — encoding, serialization, framing)
- Shape of delivery — all at once, or piece by piece over time? (section 3 — streams)
- Who drives — does the producer push, or does the consumer pull? (section 4)
- What if it fails — the boundary can be slow, drop data, or die mid-transfer. (section 5, section 6)
The core question the streaming half of this doc answers: how do you move a potentially huge amount of data across a boundary without ever holding the whole thing in memory at once? Hold that thought until section 3.
The concrete instance we'll use in Part II
To keep the abstractions honest, Part II uses one real system. Two containers run side by side in a Kubernetes pod:
-
A connector = the producer/client. It generates backup data (users, a big JSON blob, a file).
-
A sidecar = the consumer/server. It owns the cloud credentials and does the actual upload to object storage (S3).
The connector may not talk to S3 directly (credentials, separation of concerns), so it hands bytes to the sidecar over gRPC (the boundary — a network call between two containers), and the sidecar forwards them to S3.
┌─────────────┐ gRPC ┌─────────────┐ AWS SDK ┌──────┐
│ connector │ ──── bytes ──────▶ │ sidecar │ ──── upload ──────▶ │ S3 │
│ (producer / │ │ (consumer / │ │ │
│ client) │ │ server) │ │ │
└─────────────┘ └─────────────┘ └──────┘
Notice there are actually two boundaries chained here (connector→sidecar, and sidecar→S3). A recurring theme: real systems are pipelines of boundaries, and the goal is to make bytes flow through all of them as one continuous motion.
2. What is data? Bytes, encoding, serialization, framing
Before you can move data you have to be precise about what it is on the wire. At the lowest level there is only one thing:
Data crossing a boundary is always a sequence of bytes. A byte is 8 bits, a number 0–255. That's it. Everything richer — a JSON object, an image, a user record — is a convention for interpreting a byte sequence.
This matters because the producer and consumer must agree on the convention, or the bytes are meaningless on the other side. Three layers of convention sit on top of raw bytes:
2a. Encoding — bytes ↔ meaning
An encoding maps meaning to bytes and back. "A" → the byte 65 (ASCII/UTF-8). The
float 1.5 → 4 or 8 specific bytes (IEEE-754). Text needs a character encoding (UTF-8);
numbers need a byte order (endianness — big-endian vs little-endian). Get the encoding
wrong and A becomes ☺. The rule: whoever writes and whoever reads must use the same
encoding.
2b. Serialization — structure ↔ a flat byte sequence
In memory, data is a graph: a struct points to a list that points to more structs. But a boundary only carries a flat, one-dimensional stream of bytes. Serialization (a.k.a. marshaling) is flattening that graph into bytes; deserialization (unmarshaling) is rebuilding it on the other side.
| Format | Style | Trade-off |
|---|---|---|
| JSON | text, self-describing | human-readable, larger, slower to parse |
| Protobuf / gRPC | binary, schema-driven | compact, fast, needs the schema on both ends |
| Raw bytes | no structure at all | nothing to parse — the payload is the bytes |
Key cost insight, which motivates streaming later: serialization often copies the data. To send a 500 MB object as one serialized message you may hold it 2–3× in RAM at once (the original + the serialized copy + the decoded copy). This is exactly the pain section 8b describes.
2c. Framing — where does one message end and the next begin?
A stream of bytes has no built-in punctuation. If you send HELLO then WORLD, the
receiver sees HELLOWORLD — where's the split? Framing is the convention that marks
message boundaries. Common schemes:
-
Length-prefix: send the length first (
5|HELLO5|WORLD), so the reader knows to read exactly N bytes. (This is what gRPC/HTTP-2 do under the hood.) -
Delimiter: a special separator (
HELLO\nWORLD\n) — simple, but you must escape the delimiter if it can appear in the data. -
Fixed size: every message is exactly N bytes.
Framing is why a "chunk" (section 3) is a well-defined unit and not just an arbitrary cut in the byte river: the transport frames it for you.
2d. The full stack of conventions
Putting it together, one logical value crosses the boundary through these layers:
meaning ("user Alice, id 42")
│ encode + serialize
▼
bytes (a flat sequence: 7A 0A 05 41 6C 69 ...)
│ frame (mark where this message ends)
▼
frame ([length][bytes])
│ transport (TCP / HTTP-2 / pipe pushes it across)
▼
… boundary …
│ reassemble frames, deserialize, decode
▼
meaning ("user Alice, id 42") ← rebuilt on the consumer side
For the rest of the doc, when we say "bytes flow," this whole stack is what's flowing. Streaming is about doing it in pieces instead of all at once.
3. What is a stream, really?
Forget any specific technology. A stream is a simple idea:
Data delivered in pieces, over time, where you never have to hold all of it at once.
The classic analogy is a water pipe vs. a bucket:
| Bucket | Pipe (stream) | |
|---|---|---|
| How it works | Fill the whole bucket, carry it, dump it | Water flows through continuously |
| Memory needed | Big enough for everything | Only what's in the pipe at one instant |
| 500 MB file | Needs 500 MB of RAM | Needs a few KB of RAM |
With a stream you process piece N, throw it away, process piece N+1, throw it away… Your peak memory equals the size of one piece, not the total. That is the entire reason streams exist. Everything else in this doc is machinery to make that idea work in practice.
A quick numeric intuition — moving 500 MB:
-
Non-streaming ("bucket"): hold all 500 MB in memory (often several copies → 1.5 GB+, per the serialization cost in section 2b).
-
Streaming ("pipe"): 64 KB chunk at a time → peak memory ~64 KB, regardless of total size.
Three properties define a stream, and they'll recur throughout:
- Ordered — pieces arrive in the order they were sent (most transports guarantee this).
- Incremental — you can start working on early pieces before later ones exist.
- Terminated — there is an explicit "no more data" signal (an end-of-stream / EOF), distinct from "no data right now." Conflating those two is a classic bug (section 4, section 14).
A chunk is just one piece of the stream — one frame's worth of payload (section 2c). Chunk size is a tuning knob, not a correctness property: bigger chunks = fewer round-trips but more memory per piece; smaller chunks = the opposite.
4. Producers and consumers: push vs. pull, and backpressure
Once data flows in pieces, someone has to decide who controls the timing of each piece. There are exactly two answers, and understanding both is the key to the whole doc.
4a. Push vs. pull
-
Push — the producer decides when data moves. It calls
send(piece)whenever it has something, and the consumer must be ready to receive. (Think: someone throwing you balls; you'd better catch.) -
Pull — the consumer decides when data moves. It calls
read()whenever it's ready for more, and the producer must have something ready. (Think: you drawing water from a tap when you want it.)
PUSH: producer ──send()──► consumer (producer drives the clock)
PULL: producer ◄──read()── consumer (consumer drives the clock)
Neither is "better." But they compose badly when mixed: if you have a push source and a pull consumer, something has to sit in the middle and reconcile the two clocks. That "something" is an adapter (section 10 shows a real one). This mismatch is one of the most common shapes in all of systems programming.
4b. Buffering — the shock absorber
Producer and consumer rarely run at exactly the same speed. A buffer is temporary storage that holds pieces the producer has made but the consumer hasn't taken yet. It smooths out speed mismatches — but a buffer has a fixed size, and what happens when it fills is the crux of the next idea.
4c. Backpressure — the slow consumer throttling the fast producer
Backpressure = a mechanism by which a slow consumer automatically forces a fast producer to slow down, so buffers don't overflow (and you don't run out of memory).
The beautiful part: in a pull-driven system, backpressure is automatic. If the consumer pulls less often (because it's slow), the producer simply isn't asked for data, so it can't run ahead. The consumer's pace sets everyone's pace.
In a push system you must build backpressure explicitly — a flow-control window, an ack-based protocol, a bounded buffer that blocks the sender when full. Without it, a fast producer + slow consumer = unbounded memory growth = crash. (TCP and HTTP-2 both have flow-control windows for exactly this reason.)
This is the deep reason pull-based streaming is prized: it is not just memory-efficient, it is self-pacing. section 13 shows this happening for free in the real pipeline.
5. Client–server communication: the boundary, connections, and call shapes
So far "the boundary" has been abstract. In most systems it's a network call between a client and a server, so let's make that concrete and generic.
5a. Client and server, request and response
- A client initiates: it opens the conversation and asks for something.
- A server listens and responds: it waits for clients and answers.
The unit of conversation is a request → response exchange. The client sends a request; the server does work; the server sends a response. Note "client" and "producer" are not synonyms — in our sidecar, the connector is the client but also the producer of bytes, while the server (sidecar) is the consumer. Roles are orthogonal.
5b. The connection — a reusable pipe across the boundary
Before any request, the two sides establish a connection (e.g. a TCP connection, often with a TLS handshake for encryption). A connection is expensive to set up (round-trips, crypto) so systems reuse one connection for many requests (HTTP keep-alive, connection pools, HTTP-2 multiplexing many logical calls over one socket). The connection is the literal wire your framed bytes (section 2c) travel over.
Two facts about connections that shape everything downstream:
-
A connection can break at any moment — a cable, a restarted server, a timeout. Code must assume the pipe can vanish mid-sentence. (→ section 6.)
-
A connection has finite throughput and a flow-control window — you cannot shove bytes faster than it drains. This is the physical basis of backpressure (section 4c).
5c. Call shapes — how many messages flow each way
Once you allow streaming (section 3) over a connection, a single logical "call" can carry many messages in each direction. This gives four shapes — a generic taxonomy you'll see in gRPC, WebSockets, HTTP, etc.:
| Shape | Requests → Responses | When to use |
|---|---|---|
| Unary | 1 → 1 | ordinary request/response ("get user 42") |
| Server-streaming | 1 → many | one ask, a feed of answers (a live tail, search results) |
| Client-streaming | many → 1 | upload a big/continuous thing, get one ack ⭐ our case |
| Bidirectional | many ↔ many | a full conversation (chat, real-time sync) |
Client-streaming is the shape our upload uses: the client sends a stream of chunks, the server replies once at the end. The "many messages, one connection" idea is what lets bytes flow incrementally instead of as one giant blob.
5d. Half-close — how the client says "I'm done sending"
In a client-streaming call, the client sends chunk after chunk. So how does the server know which one is the last?
The answer is a half-close. When the client has no more chunks, it closes its sending half of the connection while keeping the receiving half open. In effect it says:
"I won't send anything more — but I'm still here to hear your reply."
Here's the sequence:
client: chunk → chunk → chunk → [half-close]
server: → single response
On the server, the half-close shows up as end-of-stream — the exact same "no more data" signal as an EOF. That leads to the one rule worth remembering:
The stream ending is what marks the upload complete — not any special "last message".
There is no magic sentinel chunk that means "the end." An empty chunk, for instance, is just an empty chunk; only the half-close means done. Keeping these two separate — an empty message vs. the stream closing — is what prevents an accidental empty chunk from truncating an upload early.
6. When things go wrong: timeouts, retries, idempotency, partial failure
The boundary is unreliable. A generic data-movement design is not complete until it answers "what happens when the network hiccups?" These ideas are transport-agnostic.
6a. The failure modes
| Failure | What the caller sees | The nasty part |
|---|---|---|
| Slow | nothing yet — still waiting | can't tell "slow" from "dead" |
| Dropped / connection reset | an error | may have happened before or after the server acted |
| Server crash mid-request | an error or a hang | partial work may be done |
| Response lost on the way back | an error | the server succeeded but you don't know it ⚠ |
The single hardest fact in distributed systems lives in that last row: a failed request does not mean the work didn't happen. The request may have fully succeeded and only the acknowledgement got lost. This is why retries need care.
6b. Timeouts — bounding the wait
Because "slow" and "dead" are indistinguishable, every call needs a timeout: an upper bound on how long you'll wait before giving up and treating the call as failed.
A deadline is the same idea expressed as a fixed point in time rather than a duration. Instead of "give up after 5 seconds," it says "give up at 12:00:05." That difference matters once a request passes through several services:
client ──► service A ──► service B ──► database
(deadline: 12:00:05)
The client attaches one deadline — say 12:00:05 — and it travels with the request down the whole chain. Each service checks the same clock:
- At 12:00:04, service B starts its database query — still one second left, so it proceeds.
- At 12:00:06, that query is still running. But the deadline has passed, so B stops immediately instead of finishing work whose result nobody is waiting for anymore.
Why this is better than each hop having its own private timeout: without a shared deadline, the client can give up at 12:00:05 while the database keeps grinding away for another 10 seconds — burning CPU and holding locks for a caller that already walked away. A single propagated deadline guarantees everyone downstream stops the moment the caller stops caring. (In gRPC this is the context deadline; it's carried automatically with every request.)
Set timeouts too low → you kill healthy-but-slow work and cause retries storms. Too high → you tie up resources waiting on the dead. There's no universally right value; it's a tuning decision per call.
6c. Retries — trying again, safely
When a call fails you often retry. But retries interact dangerously with section 6a's last row: if the first attempt actually succeeded, a naive retry does the work twice. Two ingredients make retries safe:
-
Idempotency — an operation is idempotent if doing it twice has the same effect as doing it once.
PUT object X = these bytesis idempotent (the second write just re-establishes the same state).append a lineorcharge $10is not — retrying duplicates it. Safe retries require idempotent operations, often via an idempotency key the server uses to dedupe. -
Backoff + jitter — don't retry instantly or in lockstep. Wait a growing interval (exponential backoff: 100ms, 200ms, 400ms…) plus a random jitter, so a fleet of clients recovering from an outage doesn't stampede the server in synchronized waves (the "thundering herd").
A retry budget (cap total retries) and a circuit breaker (stop calling a persistently-failing dependency for a cooldown, so you don't pile on) round this out.
6d. Partial failure in a stream
Streaming adds a wrinkle: a call can fail after some chunks were already processed. If the sidecar uploaded 300 MB of 500 MB and the connection dies, what's the state? Two common strategies:
-
Atomic / all-or-nothing: the consumer only "commits" the object when the whole stream completes (e.g. multipart upload that isn't finalized until the last part). A mid-stream failure leaves nothing visible — retry the whole thing. Simple to reason about.
-
Resumable: the protocol tracks an offset; a retry says "resume from byte 300 MB." Efficient for huge transfers, more protocol complexity.
Which you pick is a design choice. The important habit: always ask "what's the state if this dies at chunk N?" A stream that can't answer that will corrupt data under failure.
6e. Ordering and delivery guarantees
Finally, name your guarantee explicitly:
- At-most-once — never duplicated, may be lost. (Fire and forget.)
-
At-least-once — never lost, may be duplicated. (Retries without dedupe → this; requires idempotent consumers.)
-
Exactly-once — never lost, never duplicated. The hardest; usually emulated via at-least-once delivery + idempotent/deduplicated processing, not a true transport feature.
Most real systems choose at-least-once + idempotency because it's achievable and robust. Keep this vocabulary handy — it's the language reviewers expect when you defend a design.
Part II — The concrete instance (the sidecar → S3 pipeline)
Now every abstraction from Part I gets a real body. The running example is the connector → sidecar → S3 upload from section 1, and every section maps back to a generic idea:
| Part II section | Part I idea it makes concrete |
|---|---|
section 7 io.Reader |
the pull interface (section 4a) |
| section 8 four upload methods | representation & memory cost (section 2, section 3) |
| section 9 gRPC call shapes | client–server call shapes & half-close (sections 5c–d) |
| section 10 the adapter | push↔pull mismatch (section 4a) |
section 11 streamReader |
end-of-stream vs. no-data-yet (section 3) |
| section 13 backpressure | self-pacing pull systems (section 4c) |
| section 14 edge cases | partial failure & framing (section 6) |
7. io.Reader: Go's universal pipe of bytes
In Go, the standard way to represent "a pipe of bytes you can pull from" (section 4a) is the
io.Reader interface. It has exactly one method:
type Reader interface {
Read(p []byte) (n int, err error)
}
The contract, in plain English:
"Here's a slice
p(a pre-allocated chunk of memory). Fill it with as many bytes as you can. Tell me how many you actually wrote (n). When there's nothing left, return the special errorio.EOF."
io.EOF is the concrete end-of-stream signal from section 3. Callers use it in a loop:
buf := make([]byte, 32*1024) // a reusable 32 KB scratch buffer
for {
n, err := r.Read(buf) // pull up to 32 KB
process(buf[:n]) // use the n bytes we got
if err == io.EOF {
break // pipe is empty, we're done
}
if err != nil {
return err // a real error
}
}
Why this matters so much. In Go, almost everything that produces or consumes bytes speaks
io.Reader. Some things are a reader you can pull from:
- a file (
os.File) - a network connection (
net.Conn) - an HTTP request body
- a gzip decompressor
Other things accept a reader and pull bytes out of it — including, crucially for us, the AWS S3 uploader.
How a type "becomes" an io.Reader
A subtle but important detail: none of the types above declare that they implement
io.Reader. There is no os.File implements io.Reader written anywhere in Go.
Instead, Go uses implicit interface satisfaction: a type satisfies io.Reader simply by
having a method with the exact matching signature —
Read(p []byte) (n int, err error)
os.File has such a method, so it is an io.Reader — automatically, with no annotation.
The same is true of net.Conn, an HTTP body, and *gzip.Reader. The compiler checks the
method shape and, if it matches, the type fits the interface.
This is exactly why the "Lego brick" plugging works. Two types written years apart, by
authors who never heard of each other, fit together as long as their Read methods have the
same shape:
┌──────────────┐ satisfies ┌────────────┐ accepted by ┌──────────────┐
│ os.File │ ───────────▶ │ io.Reader │ ◀─────────── │ S3 uploader │
│ (has Read) │ (implicit) │ (contract) │ (wants one) │ (calls Read) │
└──────────────┘ └────────────┘ └──────────────┘
Neither side had to know about the other. They agree only on the one-method contract in the middle — so any byte source fits any byte consumer, like Lego bricks that all share the same studs. You can hand a file to the S3 uploader, or a network connection to the gzip decoder, and it just works.
That's the single most important idea in this doc: io.Reader is the universal pull
interface, and it's what lets us later slot a gRPC stream into an S3 uploader that has no
idea gRPC exists.
Key rules of the Read contract (they explain the code later):
Readmay return fewer bytes thanpcan hold — that's normal, not an error.n > 0witherr == io.EOFcan happen (last bytes + end at once). Handlenfirst.- Returning
(0, nil)is legal but discouraged — it means "no data right now, no error" and can make some callers spin. This is exactly the section 3 trap of confusing "no data yet" with "done." Good readers avoid it. (We'll see the code deliberately avoid it in section 11.)
8. The four ways to upload (and why each exists)
This is the best part of learning from this file: it contains four different RPCs that all do the same job — get bytes to S3 — each with different trade-offs on the section 2/section 3 axes (how the data is represented and whether it moves all-at-once or in pieces). Comparing them teaches you exactly what streaming buys you.
From proto/sidecar.proto:
service FileStoreService {
rpc GetObject(GetObjectRequest) returns (GetObjectResponse);
rpc SaveObject(SaveObjectRequest) returns (SaveObjectResponse);
rpc SaveObjectContent(SaveObjectContentRequest) returns (SaveObjectResponse);
rpc SaveObjectStream(stream SaveObjectStreamRequest) returns (SaveObjectResponse);
rpc DeleteObject(DeleteObjectRequest) returns (DeleteObjectResponse);
}
8a. SaveObject — "here's a file path"
message SaveObjectRequest { string key = 1; string local_path = 2; }
The connector writes the blob to a shared disk volume (a k8s emptyDir both containers
mount), then tells the sidecar "read it from /shared/foo.json." The sidecar reads that
file and uploads it.
- ✅ Memory-cheap (the bytes live on disk, not RAM).
- ❌ Requires a shared volume between the two containers — tight coupling.
- ❌ Writes a world-readable temp file (
chmod 0644) — a small security smell.
8b. SaveObjectContent — "here are ALL the bytes"
message SaveObjectContentRequest { string key = 1; bytes data = 2; }
The connector stuffs the entire blob into a single gRPC message — the "bucket" of section 3. Dead simple. But the proto comment spells out the serialization cost from section 2b:
the whole blob is materialized in memory 3×: read + marshal + unmarshal
Upload 500 MB → momentarily need ~1.5 GB of RAM. And gRPC enforces a max message size
(GRPC_MAX_MSG_SIZE), so beyond a threshold this fails outright. Great for small blobs,
terrible for big ones.
This is the pain that motivates streaming: holding the whole object at once doesn't scale.
8c. SaveObjectStream — "here's a stream of chunks" ⭐
message SaveObjectStreamRequest { string key = 1; bytes chunk = 2; }
The connector sends many small messages (chunks — section 3). The sidecar feeds them straight into the S3 upload as they arrive. Peak memory = one chunk. No size limit. No shared volume. This is the focus of the rest of the doc.
The comparison table
| Method | Peak memory | Bounded by gRPC msg size? | Needs shared volume? | Best for |
|---|---|---|---|---|
SaveObject |
~0 (on disk) | no | yes | when a file already exists on a shared mount |
SaveObjectContent |
whole blob ×3 | yes — fails if too big | no | small blobs already in memory |
SaveObjectStream |
one chunk | no | no | anything large, or streamed as it's produced |
SaveObjectStream is the only option that is simultaneously unbounded in size,
memory-cheap, and shared-volume-free. That's why it was added.
9. gRPC streaming: the four call shapes
This is section 5c's generic taxonomy, made concrete. gRPC supports four kinds of calls. Which one
you get is determined by where you put the stream keyword in the .proto:
| Shape | Proto syntax | Meaning | Example here |
|---|---|---|---|
| Unary | rpc F(Req) returns (Resp) |
1 request → 1 response | SaveObject, GetObject |
| Server-streaming | rpc F(Req) returns (stream Resp) |
1 request → many responses | (none here) |
| Client-streaming | rpc F(stream Req) returns (Resp) |
many requests → 1 response | SaveObjectStream |
| Bidirectional | rpc F(stream Req) returns (stream Resp) |
many ↔ many | (none here) |
SaveObjectStream is client-streaming — note stream on the request side:
rpc SaveObjectStream(stream SaveObjectStreamRequest) returns (SaveObjectResponse);
// ^^^^^^ client sends many; server replies once
On the server side, gRPC's code generator gives you a stream object
(FileStoreService_SaveObjectStreamServer) with two methods that matter:
-
stream.Recv()— block until the next chunk arrives from the client. Returnsio.EOFwhen the client has finished sending (the half-close of section 5d). Notice: the sameio.EOFsentinel from section 7 — gRPC deliberately reuses it so the stream feels like a reader. -
stream.SendAndClose(resp)— send the one final response and close the call.
So on the wire, a client-streaming call looks like:
client: chunk₁ chunk₂ chunk₃ … chunkₙ [half-close]
server: response
Send() and Recv() are decoupled by a bounded buffer
A natural question at this point: the client pushes with Send(), but the server only
pulls with Recv() — so does the client have to wait for the server to call Recv() before
each Send() returns? No. The two calls do not hand off to each other directly. Sitting
between them is a bounded buffer — gRPC's flow-control window, which lives on the
connection (section 5b). Send() pushes into that buffer; Recv() pulls out of it.
client the connection server
────── (gRPC / HTTP-2 flow-control window) ──────
Send(chunk) ─────────► [ chunk ][ chunk ][ ... ] ◄───────────── Recv()
(push into buffer) a BOUNDED buffer (pull out of buffer)
This decoupling is the section 4b "shock absorber" made concrete, and it has two consequences worth stating explicitly — one per call:
On Send() (the client side):
-
If the window has room,
Send()copies the chunk into the buffer and returns immediately. The client may run ahead — send chunk 2, 3, 4… before the server hasRecv()'d chunk 1 — up to the window size. -
If the window is full (the server hasn't been draining it fast enough),
Send()blocks until space frees up. This is the backpressure of section 13a.
On Recv() (the server side):
- If a chunk is waiting in the buffer,
Recv()returns it immediately. - If the buffer is empty (the client hasn't sent the next one yet),
Recv()blocks until a chunk arrives. This is the mirror case of section 13b.
So the precise answer to "does gRPC only receive when Recv() is called?" is two separate
facts:
-
A chunk only reaches the server's application code when it calls
Recv(). Until then, already-sent chunks just sit in the buffer, undelivered. In that sense, yes — the server "receives" only onRecv(). -
But the client's
Send()does not wait forRecv(). It pushes into the bounded buffer and moves on, stalling only when that buffer fills.
It is therefore not a lockstep ping-pong ("client sends one, server must Recv it, then
client sends the next"). It is "client pushes into a bounded buffer; server drains on its own
schedule; the buffer's size is how far the client may run ahead before it is forced to
wait." Crucially the buffer is bounded — that finiteness is exactly what makes backpressure
possible (section 13a) and keeps memory flat. If Send() could enqueue unlimited chunks without ever
blocking, a fast client + slow S3 would pile the whole object into this buffer — the very RAM
blowup streaming exists to prevent (section 8b).
A design decision baked into the message
// key must be set on the FIRST message; ignored on subsequent chunks.
// chunk may be empty (a final empty chunk is a NO-OP, not a terminator —
// the stream's END is what terminates the upload).
message SaveObjectStreamRequest { string key = 1; bytes chunk = 2; }
Two subtle rules encoded here — both are section 3/section 5d ideas in disguise:
-
keyonly on the first chunk. The destination (where in S3 to write) is metadata you only need once. The rest of the chunks are pure payload. Sending the key on every chunk would be wasteful and ambiguous. -
An empty chunk is a no-op, not "the end." What terminates the upload is the stream closing (
Recv→io.EOF, i.e. the half-close), not any special sentinel message. This is section 3's "end-of-stream ≠ no-data-right-now" rule, and it avoids a nasty class of bugs where a legitimately-empty chunk would prematurely truncate an upload.
10. Push vs. pull, and the adapter that bridges them
Here's section 4a's push/pull mismatch as a real problem. We have two components that both deal in byte-pieces but with opposite control flow:
-
gRPC stream is PUSH-shaped (from the connector's side it pushes; from ours we must actively pull each message). You decide when to ask: you call
Recv()and a chunk comes back. -
The S3 uploader is PULL-shaped. It decides when it wants data: it holds an
io.Readerand callsRead()whenever it's ready to send more to S3.
Look at what the S3 layer wants (filestore/s3.go):
func (s *S3FileStore) SaveObjectReader(ctx context.Context, key string, r io.Reader) error {
_, err := s.uploader.UploadObject(ctx, &transfermanager.UploadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: r, // ← it wants an io.Reader and will call r.Read() itself
})
return err
}
It takes an io.Reader (section 7) and calls Read() on its own schedule. But what we have is a
gRPC stream you call Recv() on. These are different shapes. We need something that
looks like an io.Reader on the outside but pulls from a gRPC stream on the inside.
That something is the adapter named streamReader — the concrete answer to section 4a's "put
something in the middle to reconcile the two clocks." This is the classic
adapter pattern: wrap object A so it
satisfies interface B.
looks like io.Reader actually calls Recv()
S3 ─────────── Read() ──────▶ streamReader ──────▶ stream.Recv() ───▶ connector
(pull) (the adapter) (push)
11. streamReader line by line
Here is the entire adapter from file_store_service.go:
// streamReader adapts a client-streamed SaveObjectStream into an io.Reader by
// pulling chunks from stream.Recv() as Read is called.
type streamReader struct {
stream sidecarv1.FileStoreService_SaveObjectStreamServer
buf []byte // leftover bytes from a chunk not yet fully handed out
}
func (r *streamReader) Read(p []byte) (int, error) {
for len(r.buf) == 0 { // (1) no leftover? fetch a fresh chunk
req, err := r.stream.Recv() // (2) pull next chunk from the client (blocks)
if errors.Is(err, io.EOF) {
return 0, io.EOF // (3) client done → end-of-stream
}
if err != nil {
return 0, err // (4) real error → propagate
}
r.buf = req.GetChunk() // (5) stash chunk; loop re-checks (could be empty!)
}
n := copy(p, r.buf) // (6) copy as much as fits into p
r.buf = r.buf[n:] // (7) keep the remainder for next call
return n, nil // (8) report how many bytes delivered
}
Why the buf field must exist
When S3 calls Read(p), it chooses how big p is — say 32 KB. But the chunk you got
from Recv() might be 1 MB. You can only copy as much as fits into p. So you copy
32 KB now and must remember the other ~968 KB for the next Read. That remainder lives
in buf. Without buf, you'd lose bytes every time p is smaller than a chunk. This is the
buffering of section 4b, at its smallest scale.
The two sizes are independent
- Chunk size = how big the connector's messages are (client's choice — section 3's tuning knob).
psize = how big a bite the S3 uploader asks for (uploader's choice).
They have nothing to do with each other. streamReader's whole job is to reconcile the
two: buffer a whole chunk, then dole it out in whatever bite-sizes the reader asks for.
Line-by-line
-
(1)
for, notif— this is the subtle, correct choice. Recall an empty chunk is legal (section 9). IfRecv()returns an empty chunk,r.bufis still length 0. With anif, the code would fall through andcopy0 bytes → return(0, nil)— the discouraged "no data, no error" result from section 7 (and section 3's "no data yet" ≠ "done" trap) that can spin callers. Theforloop instead simply loops and fetches the next chunk, transparently skipping empties. -
(2)
Recv()blocks. If the connector hasn't sent the next chunk yet, this waits. That blocking is good — it's the natural pacing mechanism / backpressure (see section 13). -
(3)
io.EOF→io.EOF. The client half-closing the stream (section 5d) becomes end-of-reader. The two worlds' "done" signals line up perfectly because gRPC reusesio.EOF. -
(5)
copysemantics.copy(dst, src)copiesmin(len(dst), len(src))bytes and returns that count. Son = min(len(p), len(r.buf))— exactly "as much as fits." -
(7)
r.buf = r.buf[n:]is a re-slice, not a copy. It just moves the slice's start pointer forward past the consumed bytes. Cheap — no allocation, no memory shuffling.
How the handler wires it up
func (s *fileStoreServer) SaveObjectStream(stream sidecarv1.FileStoreService_SaveObjectStreamServer) error {
if s.store == nil {
return status.Error(codes.Unimplemented, "file store not configured (set FILE_STORE_BUCKET)")
}
first, err := stream.Recv() // pull chunk #1 (carries the key)
if errors.Is(err, io.EOF) {
return status.Error(codes.InvalidArgument, "at least one chunk with key is required")
}
if err != nil {
return status.Errorf(codes.Internal, "recv: %v", err)
}
if first.GetKey() == "" {
return status.Error(codes.InvalidArgument, "key is required on the first chunk")
}
key := s3Key(first.GetKey()) // extract destination key
r := &streamReader{stream: stream, buf: first.GetChunk()} // SEED buf with chunk #1's payload
if err := s.store.SaveObjectReader(stream.Context(), key, r); err != nil {
return status.Errorf(codes.Internal, "save object stream: %v", err)
}
return stream.SendAndClose(&sidecarv1.SaveObjectResponse{}) // one final response
}
The one thing to notice: the handler pulls the first chunk itself (to read the key —
the "metadata on the first message" rule from section 9), then seeds streamReader.buf with that
first chunk's payload so those bytes aren't lost. From then on, SaveObjectReader's calls
to Read drive Recv for all the remaining chunks. The first chunk was already in hand;
the rest are pulled on demand.
12. The full journey of one byte
Let's trace what happens when the S3 uploader wants more data — this is the whole pipeline of boundaries from section 1 flowing as one motion. Every arrow is a function call:
S3 transfer manager needs bytes to send
│
▼ calls
streamReader.Read(p) ── "give me up to len(p) bytes"
│
├─ buf still has leftover? → copy from buf, return. (no network!)
│
└─ buf empty? → calls
stream.Recv() ── blocks until the connector sends the next chunk
│
▼ over the gRPC connection (the boundary)
connector.Send(chunk) ── the client pushes one SaveObjectStreamRequest
│
▼
chunk arrives → stored in buf → copied into p → returned to S3
│
▼
S3 transfer manager sends those bytes to S3, then asks for more → loop repeats
│
▼ when connector half-closes, Recv → io.EOF → Read → io.EOF
S3 upload finalizes → SaveObjectReader returns nil → SendAndClose → done
The critical observation: the whole chain is driven from the S3 end (pull). Data is requested top-down and delivered bottom-up, one bite at a time. At no point does anyone hold more than roughly one chunk. The upload starts as soon as the first chunk lands — it does not wait for the connector to finish sending. Connector → sidecar → S3 all flow together as one continuous pipeline.
This is exactly what the handler's doc comment promises:
the upload starts before the stream finishes and never buffers the whole object in sidecar memory or on the shared volume.
13. Backpressure in this pipeline: the advanced payoff
This is section 4c's self-pacing property, happening for free. Backpressure = a slow consumer automatically forcing a fast producer to slow down, so buffers don't overflow.
The claim of this section is stronger than "backpressure works." It's that a pull pipeline self-paces to its slowest link, automatically, in both directions. Whichever side is slower, the faster side blocks and waits — and crucially, nothing accumulates in between. section 13a walks the fast-producer case (the classic backpressure story). section 13b walks the mirror case: a slow producer and a fast consumer. section 13c shows they are one mechanism seen from opposite ends.
13a. Fast producer, slow consumer — the producer gets throttled
Because the chain is pull-driven, the speed of S3 sets the pace of everything:
S3 is slow to accept bytes
→ S3 uploader calls Read() less often
→ streamReader calls Recv() less often
→ gRPC's flow-control window fills (the §5b connection window)
→ the connector's Send() blocks
→ the connector naturally slows down producing
Nobody wrote any of that throttling logic. It emerges from the pull model:
-
If you had used
SaveObjectContent(push everything at once), a fast connector + slow S3 = the whole blob piles up in the sidecar's RAM. No backpressure. -
With
SaveObjectStream(pull on demand), the connector can only get as far ahead as gRPC's flow-control window allows, then it blocks. Memory stays flat no matter how large the object or how mismatched the producer/consumer speeds.
This is the deep reason streaming is not just "memory-efficient" but also self-pacing — exactly the claim section 4c made generically.
13b. Slow producer, fast consumer — the consumer gets throttled (the mirror case)
Now flip the speeds. Suppose the thing producing bytes is slow — imagine the connector is
streaming a git pack it's still computing, at 10 MB/s — while the S3 uploader is fast and
would happily accept 100 MB/s. You (the sidecar) are the consumer of that incoming stream,
forwarding it to the AWS uploader, which pulls from you via Read().
git pack ──► sidecar / streamReader ──► S3 uploader ──► S3
(slow producer, 10 MB/s) (fast, pulls via Read, wants 100 MB/s)
The uploader is pull-shaped (section 10): it calls Read() whenever it is ready for more. It's
fast, so it's ready constantly — it wants the next bite the instant it finishes the last one.
Follow one such Read() down the chain:
S3 uploader.Read(p) ── "give me bytes NOW, I'm ready"
└─ streamReader.Read(p)
└─ buf empty → stream.Recv()
└─ BLOCKS ⏸ ── the connector hasn't produced the next chunk yet
Recv() blocks (section 11 line (2)). It does not return (0, nil), it does not spin, it
does not fabricate an EOF. The goroutine simply parks until the connector actually hands
over the next chunk. The fast uploader is now sitting idle, frozen inside its own Read(),
waiting. The moment the connector coughs up a chunk, Recv() unblocks, returns the bytes, the
uploader consumes them at its blazing speed… and immediately calls Read() again, and blocks
again.
So the throttling still happens — but this time it throttles the consumer, not the producer:
git pack is slow to produce bytes
→ Recv() has nothing to return, so it blocks
→ streamReader.Read() blocks (it's waiting on Recv)
→ the S3 uploader's Read() call blocks
→ the fast uploader idles, pinned to the connector's 10 MB/s pace
Just like section 13a, nobody wrote this throttling logic — it emerges from the pull model. In
section 13a it was Send() that parked (the producer waiting on a full flow-control window); here
it's Recv() that parks (the consumer waiting on an empty pipe). Same self-pacing, opposite
end of the chain.
Why this direction is the benign one — nothing accumulates
Here is the key property, and it's the reason a slow producer is never a memory problem:
Memory only piles up when data arrives faster than it's consumed. In the slow-producer case, data arrives slower than it's consumed — so a backlog is physically impossible.
The consumer drains each chunk instantly and then waits, empty-handed, for the next. buf in
streamReader (section 11) is empty essentially all the time; peak memory is still ~one chunk, and in
practice less, because the buffer rarely holds anything between reads. There is no window to
overflow, no queue to grow.
The only real "cost" is that your fast uploader is underutilized — it spends most of its
life blocked, waiting on git. That is not a bug; it is exactly correct. You physically cannot
upload bytes that have not been produced yet, and the uploader idling politely (rather than
busy-spinning or erroring) is the desired behavior. This is also why the section 7 rule against
returning (0, nil) matters: a well-behaved reader blocks when it has no data yet, instead
of returning "no data, no error" and burning CPU in the caller's loop.
Relate this back to the original question people ask about this pipeline: "I'm the consumer of
the incoming stream — I decide how fast I pull, right?" Yes, but only up to a ceiling. You
can always choose to pull slower (and section 13a shows that slowing you down propagates back and
throttles the producer). You can never pull faster than the producer can produce — try to,
and you simply block in Recv() until the next chunk exists.
13c. The symmetry, in one table
Both cases are the same pull mechanism, observed from opposite ends. The pipeline always runs at the speed of its slowest link, and only the fast side ever blocks:
| section 13a — fast producer, slow consumer | section 13b — slow producer, fast consumer | |
|---|---|---|
| Who is slow | S3 (the consumer) | git pack / connector (the producer) |
| Who blocks (waits) | the producer, in Send() |
the consumer, in Recv() / Read() |
| Why it blocks | gRPC flow-control window is full (section 5b) | the pipe is empty — no chunk yet |
| What would accumulate | the whole blob, in sidecar RAM… | nothing — data arrives slower than it drains |
| …and what prevents it | flow control + the pull model (blocks the sender) | nothing needs preventing — a backlog is impossible |
| Pipeline throughput | pinned to S3's speed | pinned to the connector's speed |
| Risk level | dangerous without pull (a push design piles up RAM) | benign — self-throttles with zero risk |
The takeaway: a pull pipeline is self-pacing in both directions and holds ~one chunk regardless of which side is faster. The slow-producer case (section 13b) is the harmless one — it just leaves a fast consumer waiting. The fast-producer case (section 13a) is the one that would be dangerous under a push design, and is exactly what pull-based streaming defuses for free.
14. Edge cases and why the code is shaped this way
Each row here is a section 6 failure/edge idea made concrete:
| Situation | What happens | Why it's correct |
|---|---|---|
| Client sends zero chunks | First stream.Recv() returns io.EOF → handler returns InvalidArgument("at least one chunk with key is required") |
Can't upload with no key; fail fast and clearly. |
| First chunk has empty key | Handler returns InvalidArgument("key is required on the first chunk") |
The destination is mandatory; section 9's "key on first chunk" rule enforced. |
| A middle chunk is empty | streamReader.Read's for loop sees len(buf)==0, loops, fetches the next chunk |
Empty chunk is a no-op (section 9), not a terminator — no truncated upload. |
Chunk bigger than p |
copy takes len(p) bytes; remainder kept in buf for next Read |
The whole reason buf exists (section 11) — buffering (section 4b). |
| Network error mid-stream | Recv returns a non-EOF error → Read returns it → SaveObjectReader fails → handler returns Internal |
Errors propagate up the same pull chain; the S3 upload aborts. This is section 6d partial failure: the multipart upload is never finalized, so a dead stream leaves nothing in S3 — retry the whole thing (all-or-nothing). |
s.store == nil |
Handler returns Unimplemented immediately |
Sidecar started without FILE_STORE_BUCKET; nothing to upload to. |
| Final chunk carries last bytes + then EOF | Bytes delivered first (buf non-empty), EOF surfaces on the next Read |
Matches io.Reader contract; no bytes dropped. |
A note on why SaveObjectContent still exists even though SaveObjectStream is
strictly more scalable: for small, already-in-memory blobs, a single unary call is simpler
(one request, one response, no chunk loop) and the memory cost is negligible. Streaming adds
value precisely when the data is large or produced incrementally. Right tool, right job.
What about retries (section 6c)? Because the destination is a PUT-style object write keyed by
key, re-running the whole upload is idempotent — a retry just re-establishes the same
object bytes at the same key, overwriting any partial state. That's what makes the
"fail → retry the whole stream" strategy above safe.
Glossary
Generic (Part I):
- Producer / consumer — the source that has bytes vs. the sink that wants them.
-
Boundary — the gap (network hop, process/disk boundary) the data must cross; it has cost and can fail.
-
Encoding — the convention mapping meaning ↔ bytes (UTF-8, IEEE-754, endianness).
-
Serialization / marshaling — flattening an in-memory structure into a byte sequence; deserialization rebuilds it.
-
Framing — the convention marking where one message ends and the next begins (length-prefix, delimiter, fixed size).
-
Stream — data delivered in pieces over time; you never hold all of it at once.
- Chunk — one piece of a stream (one frame's payload).
- End-of-stream / EOF — the explicit "no more data" signal, distinct from "no data yet."
- Push vs. pull — push: the producer decides when data moves; pull: the consumer decides.
- Buffer — temporary storage holding produced-but-not-yet-consumed pieces.
-
Backpressure — a slow consumer automatically throttling a fast producer so buffers don't overflow; automatic in pull systems.
-
Flow-control window — a bounded buffer on a connection that decouples the sender from the receiver:
send/Send()pushes into it and returns while there's room, blocking only when it's full;recv/Recv()drains from it, blocking when it's empty. Its finite size is what makes backpressure possible and keeps memory flat (TCP and HTTP-2/gRPC both have one). -
Client / server — the side that initiates vs. the side that listens and responds (orthogonal to producer/consumer).
-
Connection — the reusable pipe across the boundary (TCP/TLS); expensive to set up, reused for many calls, can break anytime, has a finite flow-control window.
-
Call shapes — unary (1→1), server-streaming (1→many), client-streaming (many→1), bidirectional (many↔many).
-
Half-close — the client signalling "done sending" while still able to receive.
-
Timeout / deadline — an upper bound on how long to wait; a deadline propagates through a pipeline.
-
Retry / backoff / jitter — try again; wait a growing + randomized interval to avoid stampedes.
-
Idempotency — doing an operation twice has the same effect as once; the precondition for safe retries.
-
Delivery guarantee — at-most-once / at-least-once / exactly-once.
Concrete (Part II):
-
io.Reader— Go's one-method interface (Read(p []byte) (int, error)) for pulling bytes; the universal pull interface made real. -
io.EOF— the sentinel error meaning "no more data"; reused by bothio.Readerand gRPC'sRecv(). -
Recv()/SendAndClose()— server-side methods on a client-streaming gRPC call: pull the next request; send the single final response. -
Adapter — an object that wraps A to satisfy interface B.
streamReaderwraps a gRPC stream (push) to satisfyio.Reader(pull).
Exercises
Test your understanding (answers are all in the doc above):
On the generic model (Part I):
-
Name the three always-present pieces of a data-movement problem, and the four questions the boundary forces you to answer.
-
Why can't you deserialize a message correctly if you don't know its framing?
-
What's the difference between "no data right now" and "end of stream," and what bug appears if you conflate them?
-
Why is backpressure automatic in a pull system but something you must build in a push system?
-
A request fails with a network error. Why can't you conclude the work didn't happen — and what two properties make it safe to retry anyway?
On the concrete instance (Part II):
- Why does
streamReader.Readuse aforloop instead of anifwhenbufis empty? -
If the S3 uploader calls
Readwith a 16 KBp, but the current chunk is 1 MB, how manyReadcalls does it take to drain that one chunk? What holds the leftover? -
The connector produces data at 100 MB/s but S3 only accepts 10 MB/s. Where does the excess go, and what stops the sidecar from running out of memory? Trace it to the gRPC flow-control window. 8b. Now flip it: the connector produces at 10 MB/s but S3 would accept 100 MB/s. Which side blocks now, in which call, and why does no memory accumulate this time? Why is a fast consumer sitting idle the correct behavior rather than a bug? (section 13b)
-
Why is the
keyonly on the first chunk and not every chunk? - What would break if an empty chunk were treated as "end of stream" instead of a no-op?
-
SaveObjectContentandSaveObjectStreamboth avoid the shared volume. Give one concrete scenario where you'd still preferSaveObjectContent, and one where it would fail butSaveObjectStreamwould succeed. -
If the network dies after 300 MB of a 500 MB stream, what is left in S3, and why is retrying the whole upload safe?
See also
file_store_service.go— the gRPC handlers +streamReader.filestore/s3.go—SaveObjectReader, the S3 upload consumer.filestore/filestore.go— theFileStoreinterface.proto/sidecar.proto— the RPC + message definitions.- Go docs:
io.Reader· gRPC client-streaming