# Streaming SQL to Parquet on a Bucket

*By Shai Ben-Yehuda · Nov 2026*

```bash
$ bcp "SELECT * FROM sales" | duckdb "TO PARQUET" | node "write to bucket"
```

☕ This paper follows *Why Parquet Structure Matters for Fast Queries* and *Faster Parquet with a Column Cache*. There is a summary table at the end, followed by references.

The first two papers read Parquet from a bucket.

This one writes it: how do we download a huge SQL table into a Parquet file on a bucket, and be sure the download never gets stuck?

SQL Server can send us endless data, and the bucket can absorb endless data. Only our process, in the middle, is bounded: however big
the machine, its memory, disk and cores are finite, and an endless table will outgrow them.

![SQL Server and the bucket are endless; bcp and duckdb in the bounded middle](https://multitrail.com/blog/streaming-sql-to-parquet/assets/hero.webp)

## Part I — The Problem: It Will Get Stuck

# 1. One Query, Billions of Rows

Our coffee network keeps its sales in SQL Server, at headquarters.

The dashboards read Parquet from a bucket.

So the sales must leave SQL Server and land in the bucket as Parquet: the changed rows every hour, and the whole table when we start over.

Our sales lines table has about 80 million rows, and that is a small one.

A bigger network, a few years of history, or an event log can easily reach **billions of rows**.

The obvious way has three steps:

```text
SQL Server ──query──► rows in memory ──write──► file on disk ──upload──► bucket
```

Fetch the rows, write a file, upload the file.

On a laptop, with a small table, it works.

It is tested, it is green, and it goes to production.

> **The obvious download keeps the table somewhere before it reaches the bucket.**

---

# 2. It Will Get Stuck

Every step that keeps the table needs resources that grow with the table.

**Memory grows with the table.**

* a driver that fetches the result into a list or a data frame;
* batches written into a structure that is still held;
* a converter that reads a whole intermediate file before it writes Parquet.

**Disk grows with the table.**

* a staging CSV or JSON file;
* the complete Parquet file, waiting for its upload;
* one more copy on every hop: a VM, a laptop, the bucket.

## Every Value Becomes an Object

A typical download reads the rows through a driver in Python, Node or Java.

The driver turns every row into an object, and every value inside it into another object.

```text
SQL Server row (binary)          Python row (pymssql, as_dict=True)
┌──────────────────────┐         dict ─┬─ 'C'        → int        28 B
│ ~100–150 bytes       │   ───►        ├─ 'Nm'       → str        49 B + text
└──────────────────────┘               ├─ 'Price'    → Decimal   104 B
                                       ├─ 'DateDoc'  → datetime   48 B
                                       └─ … × 20 columns
                                       dict itself  ~650 B
                                       ≈ 1.5 KB per row
```

Approximate CPython object sizes (`sys.getsizeof`), for a 20-column row. Illustrative, but the order of magnitude is real:

| | One row | 10M rows | 1B rows |
| --- | ---: | ---: | ---: |
| In the source (binary) | ~120 B | ~1.2 GB | ~120 GB |
| As Python objects | ~1.5 KB | ~15 GB | ~1.5 TB |
| Objects created | ~21 | ~210 million | ~21 billion |

Reading in batches (`fetchmany`) keeps the memory bounded, but it does not remove the work.

Every one of those objects is:

1. **allocated** while the driver decodes the row;
2. **converted**, to text, JSON or a data-frame cell, so the next step can write it;
3. **freed**, and its container watched by the garbage collector.

Python's cyclic garbage collector runs every few hundred container allocations, and each pass walks the objects still alive. A large batch held in memory makes every pass longer.

All of this runs on one core, under one interpreter lock.

```text
CPU per row (illustrative)

python driver   decode ████  objects ██████  convert █████  free + GC ████
bcp | duckdb    bulk text █   typed column vectors ▏
```

Then the next step parses the text or JSON again, to build Parquet.

The same value is decoded, turned into an object, turned into text, and parsed back: four times, for each of billions of values.

Our old producer did exactly this. It measured one Python row with `sys.getsizeof`, divided a tenth of the machine's free memory by it to
choose a batch size, wrote gzip JSONL to a temp directory, and let DuckDB read it back with `read_json_auto`.

It was careful, and it still scaled with the table: in CPU, in disk, and in time.

## Memory and Disk Grow Together

```text
Memory and disk needed (illustrative)

table rows        10M     100M       1B+
keeps the table   ▏       ████       ██████████████████████████████  > the machine
streams           ▏       ▏          ▏                               flat
```

Past some size, the process does not fail cleanly. It gets stuck:

* garbage collection takes longer and longer;
* the machine starts to swap;
* the engine spills to a temp directory, which is disk again;
* the disk fills, and a write blocks or leaves a truncated file;
* the out-of-memory killer ends the process at 70%, and the next run starts from zero.

The worst part: **we do not know in what conditions.**

| Condition | Why we cannot test it away |
| --- | --- |
| The table grows | 80M rows today, billions in a few years |
| A new client | a bigger database, the same code |
| Starting a table over | the whole history, not one hour of changes |
| A slower link | the same rows stay in memory longer |
| Another process on the machine | less memory left than in the test |

A test that passes proves only that this size, on this machine, on this day, fits.

> **A download whose memory or disk grows with the table will get stuck. We just do not know when.**

---

# 3. A Bigger Machine Only Moves the Wall

The first reflex is a bigger machine.

It works, until the table, or the next client, is bigger again.

```text
machine                                  stuck at (illustrative)
 1 vCPU ·   2 GiB mem ·  10 GB disk      ████▌
 8 vCPU ·  32 GiB mem · 500 GB disk      ███████████████▌
64 vCPU · 512 GiB mem ·  10 TB disk      ██████████████████████████████▌
endless table                            ──────────────────────────────────────────────►
```

There is a second surprise on a small lambda.

Its disk is not a disk. In Cloud Run, the local file system lives in memory, inside the same 2 GiB the job runs in.

So a staging file is not "on disk": it is in memory too.

The only safe design is one whose memory and disk do not depend on the size of the table at all:

| Resource | Must be |
| --- | --- |
| Memory | a fixed amount, for 1M rows or 1B rows |
| Local disk | nothing |
| Time | allowed to grow with the table |
| The bucket | holds everything; it never runs out |

## Two Endless Ends, a Bounded Middle

Look at the two ends of the download.

SQL Server can send us endless data: a billion rows, ten billion, for as long as the query runs.

The bucket can absorb endless data: object after object, terabyte after terabyte.

Only the middle is bounded.

It may be a small lambda with 1 vCPU and 2 GiB, or a large server with 64 cores, 512 GiB of memory and terabytes of disk. Either way it has a size, and the two ends do not.

```text
SQL Server   ∞ rows  ───►  ┌──────────────────────┐  ───►  ∞ bytes   bucket
endless source             │     our process      │        endless sink
                           │ X mem · Y disk · Z   │
                           │ cores: always bounded│
                           └──────────────────────┘
```

The middle must never try to hold what flows through it.

It must be a pipe, not a tank.

And because only the middle can break, everything in the middle must be resilient (Part III).

> **Make size a matter of time only: memory flat, disk zero.**

---

## Part II — The Pipe: bcp | duckdb | Parquet on a Bucket

# 4. Why the Parquet Footer Is at the End

Before the pipe, one question: can a Parquet file be written as a stream at all?

Many file formats cannot. They start with a header that describes the whole file: how many rows, where each part begins.

A writer cannot know that before it has seen all the data. So it must either keep the whole file until the end, or go back and rewrite the header.

Neither works for us. A pipe cannot go back. A resumable upload cannot go back. And keeping the whole file is the tank we refuse to build.

## Parquet Describes Itself at the End

The first paper showed the footer as the reader's map: min/max statistics and the location of every column chunk.

That map is at the **end** of the file, and this is what makes streaming possible.

```text
┌──────┬──────────┬──────────┬─────┬──────────┬──────────────────┬────────┬──────┐
│ PAR1 │ RG 0     │ RG 1     │  …  │ RG n     │ footer           │ length │ PAR1 │
│      │ columns  │ columns  │     │ columns  │ schema, stats,   │ 4 B    │      │
│      │          │          │     │          │ offsets, sizes   │        │      │
└──────┴──────────┴──────────┴─────┴──────────┴──────────────────┴────────┴──────┘
  start                                         written last
```

So the writer builds the file in one pass, front to back, and never looks back:

```text
time ──►

PAR1
PAR1 | RG 0                                   RG 0 sent: its offset and stats are noted
PAR1 | RG 0 | RG 1                            RG 1 sent
PAR1 | RG 0 | RG 1 | … | RG n                 the last rows arrive
PAR1 | RG 0 | RG 1 | … | RG n | footer | PAR1 now everything is known: write the map
```

Each row group is complete the moment it is written. Its bytes can leave at once, into a pipe, into an upload, into the bucket.

Only the footer waits for the end, and the footer is small: a few hundred bytes per column chunk. For our largest table, 55 row groups, it is kilobytes, not gigabytes.

## The Same Footer, Read First

The reader does the opposite: it reads the file from its end.

It fetches the last bytes, finds the footer's length and the map, and only then fetches the column chunks it needs. That is how the second
paper's cache starts every file: one small request for its tail.

```text
writer:  front ──────────────────────────────► end   (one pass, append only)
reader:  end ◄── footer first, then only the chunks it needs
```

One layout serves both: the writer streams it, the reader skips through it.

> **The footer is at the end so the writer never has to look back: a Parquet file can be built while it streams.**

---

# 5. Three Processes, Two Pipes

Unix has had the answer for fifty years: a pipe.

```text
SQL Server ──bcp──► rows.pipe ──duckdb──► parquet.pipe ──node──► bucket
           text '|'           typed rows               8 MB chunks
                              → Parquet                → one file
```

Three processes, connected by two named pipes:

* **bcp**, SQL Server's bulk-copy tool, runs one query and writes the rows as `|`-separated text into `rows.pipe`;
* **duckdb** reads that text as typed columns and writes Parquet into `parquet.pipe`;
* **node** reads the Parquet and uploads it to the bucket in 8 MB chunks.

A named pipe has no size on disk. It is a small kernel buffer between a writer and a reader.

When the reader is slow, the writer waits. When the writer is slow, the reader waits.

So the whole table flows through, but only a little of it exists at any moment.

```text
where the bytes are, at any moment

rows.pipe        a kernel buffer
duckdb           one row group being built (~100 MB)
node             one 8 MB chunk
local disk       nothing
bucket           everything already sent
```

DuckDB writes straight into the pipe (`USE_TMP_FILE false`), so it never builds the file locally first.

No value ever becomes an object.

bcp is native code: it turns SQL Server's bulk protocol into text without a row object or a value object. DuckDB parses that text straight
into typed column vectors of 2,048 values, and encodes them into Parquet.

```text
python driver   row → dict → 20 objects → text → parse → Parquet      (per value)
bcp | duckdb    bulk stream → text → column vector → Parquet          (per 2,048 values)
```

One query, in the source's own order, with no `ORDER BY`: sorting made SQL Server measurably **4.5× slower** before the first row arrived.

> **Every byte is in exactly one place at a time: in a pipe, in a row-group buffer, or on its way to the bucket.**

---

# 6. How the Middle Says Stop

This is the hard part.

The source can send faster than the bucket takes, or the bucket can slow down for a moment.

Either way, the bytes in between must go somewhere. If any stage keeps them, the pipe quietly becomes a tank again.

So the middle must be able to say **stop**, all the way back to SQL Server.

## The Stop Travels Upstream

Nothing in our pipe pushes. Every stage pulls only when it is ready.

When the end slows down, the stop travels back, one stage at a time:

```text
bucket slow    → node awaits its PUT, and stops reading parquet.pipe
parquet.pipe   → fills (64 KiB, kernel) → duckdb's write() blocks
duckdb         → stops reading rows.pipe
rows.pipe      → fills (64 KiB, kernel) → bcp's write() blocks
bcp            → stops reading its socket → TCP window closes
SQL Server     → its send blocks: the query waits (ASYNC_NETWORK_IO)
```

Nobody buffers the excess. Each stage stops pulling, and the last stop is plain TCP flow control.

The same happens through the port forward on the VM in front of SQL Server: it copies with small blocking buffers, so the window closes on both hops.

## Why bcp Will Not Push More

**bcp has no queue.** It is simple synchronous C: read rows from the network, format them, `write()` them. When `write()` blocks, bcp stops reading the network.

Its memory is measured flat at **12 MB**, for 216K rows and for 52M rows alike.

**The kernel enforces it, not our code.** bcp and DuckDB talk directly through `rows.pipe`, and the pipe belongs to the kernel, not to either of them.

A pipe is a fixed buffer inside the kernel: 64 KiB by default on Linux (16 pages). Unix defines what happens at its edges (`pipe(7)`):

```text
writer calls write()  →  buffer has room  →  bytes copied, write() returns
writer calls write()  →  buffer is full   →  the kernel puts the writer to sleep
reader calls read()   →  bytes taken      →  the kernel wakes the writer
reader calls read()   →  buffer is empty  →  the kernel puts the reader to sleep
all writers closed    →  read() returns 0 →  end of file
```

The waiting happens inside the system call. bcp does not decide to wait, and neither does our code: bcp calls `write()`, and the call simply does not return until DuckDB has read.

While it sleeps, the process uses no CPU, and `/proc/<pid>/wchan` shows where: `pipe_write` for a writer on a full pipe, `pipe_read` for a reader on an empty one.

So the buffer between bcp and DuckDB cannot grow: it is 64 KiB because the kernel says so. There is no queue to configure, and nothing we could forget to handle.

This is the oldest flow control in Unix. `ls | less` has worked this way since the 1970s.

**SQL Server pauses instead of buffering.** A plain `SELECT` scan produces rows only as fast as the client reads them. While we do not read, the query simply waits.

That is the second reason for no `ORDER BY`: a sort must finish on the server before the first row is sent, so the server would hold the whole result in memory or in `tempdb`.

## Common Bug: Push Without Listening

Node is the one place where an endless buffer is easy to write by accident.

This line looks like a pipe. It is a bug:

```js
bcp.stdout.on('data', chunk => duckdb.stdin.write(chunk))
```

`'data'` fires as fast as bcp produces. `write()` never blocks: when DuckDB is slower, it returns `false`, which means "my buffer is full, stop".

Nobody listens. Every chunk is accepted anyway, and waits in node's memory.

```text
bcp ──fast──► node: write() → false, ignored ──► [ buffer grows with the table ] ──slow──► duckdb
```

It is the tank again, hidden in one line. And it passes every small test.

## Four Ways to Fix It

**1. Do not put node in the middle.** Let bcp write straight into a pipe that DuckDB reads. The kernel blocks bcp when the pipe is full.

**2. Let Node connect the streams.**

```js
await pipeline(bcp.stdout, duckdb.stdin)
```

`pipeline` listens to `false`: it pauses the source, and resumes it on `'drain'`. It also passes errors on and closes both ends.

**3. Listen to `false` by hand.**

```js
if (!duckdb.stdin.write(chunk)) { bcp.stdout.pause(); duckdb.stdin.once('drain', () => bcp.stdout.resume()) }
```

A paused source stops reading bcp's output, that pipe fills, and bcp blocks: back to the kernel.

**4. Pull instead of push.**

```js
for await (const data of parquetIn) { ... await target.write(chunk) ... }
```

The next piece is read only after the previous one was accepted. While the loop waits, the read stream stops at 1 MB.

| Fix | Who stops the writer | Easy to get wrong? |
| --- | --- | --- |
| 1. No node in the middle | the kernel | no: nothing to forget |
| 2. `pipeline` | Node streams | rarely |
| 3. `write()` and `'drain'` by hand | our code | yes: one missed path is enough |
| 4. `for await` and `await` | the pull loop | rarely |

The rule behind all four: **a stage may take the next bytes only after the stage after it accepted the previous ones.**

## Every Buffer Has a Bound

| Place | Holds at most | Bounded by |
| --- | --- | --- |
| SQL Server | the network packets of a paused query | the TCP window |
| port forward | a small copy buffer per direction | blocking writes |
| bcp | a few rows (12 MB of memory) | blocking `write()` |
| `rows.pipe` | 64 KiB | the kernel |
| DuckDB | the CSV read buffer and one row group (~100 MB) | `ROW_GROUP_SIZE`, `memory_limit` |
| `parquet.pipe` | 64 KiB | the kernel |
| node | 1 MB read buffer, up to 8 MB of parts | the pull loop |
| upload | one 8 MB chunk in flight | the awaited PUT |

Add the rows up: every bound is fixed. None of them depends on the size of the table.

## Bursts, Not a Flood

The flow is not smooth.

DuckDB emits Parquet in bursts, one row group at a flush: about 11 MB for the sales lines (616 MB ÷ 55 row groups). Between flushes, nothing comes out.

```text
SQL Server → bcp → duckdb    ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁   steady: 7–13 MB/s, the source link
duckdb → node → bucket       ▁▁▁▁▁█▁▁▁▁▁█▁▁▁▁▁█▁▁▁▁▁█   a burst per row group
```

Normally the source link is the slowest stage, so backpressure engages only for a moment, at each flush.

When an upload chunk is retried, up to 120 seconds, three times, everything upstream pauses with it: DuckDB, bcp and the SQL Server query. Nothing grows meanwhile.

A paused query keeps its connection and its place in the scan on the source. So a fast middle is also polite to the source: its pauses stay short.

> **The middle never keeps what it cannot pass on: it stops pulling, and the stop travels back to SQL Server as a full pipe and a closed TCP window.**

---

# 7. Careful Setup: From the Sink to the Source

Backpressure works only once every stage is connected.

Before that, during setup, there is a short moment when a stage may write into a pipe that nobody reads yet.

That moment can lose data.

## The Wrong Order Loses Rows

Start the stream the natural way, from the source:

```text
WRONG: source first

1. bcp starts       → runs the query, writes rows into rows.pipe
2. duckdb starts    → not reading yet
3. node starts
```

A named pipe is not a file. Its bytes live in a kernel buffer that exists only while someone has the pipe open.

Normally a writer cannot get ahead of its reader: `open()` for writing blocks until a reader opens the other end (`fifo(7)`).

But Linux has an exception. Opening a FIFO for **read and write** (`O_RDWR`) never blocks, because the process is then a reader of its own
pipe. The same is true whenever any other process holds the read end for a moment: a helper, a probe, a cleanup step.

Then the writer is not stopped. A small table, say a few hundred rows, fits entirely in the 64 KiB buffer. bcp writes it, closes the pipe, and exits with success.

When the last process holding the pipe closes it, and DuckDB has not opened it yet, the kernel frees the buffer. The rows are gone.

DuckDB then opens an empty pipe, waits for a writer that already left, sees end of file, and writes a perfectly valid Parquet file with **zero rows**.

```text
bcp:     exit 0, "312 rows copied"
duckdb:  exit 0
bucket:  Store-master-….parquet   ✓ valid   0 rows
```

Every process succeeded. Nothing failed. The data is simply gone.

This is the worst kind of failure: silent, and green.

## The Right Order: Every Reader Before Its Writer

So the stream starts from its sink back to its source:

```text
RIGHT: sink first

1. the upload session      ready to receive
2. node                    reading parquet.pipe
3. duckdb                  started, and seen waiting on rows.pipe
4. bcp                     only now runs the query
```

Each stage is started only when the stage after it is already listening.

So the first byte bcp writes already has a reader, and the reader already has a place to send it.

## Seeing That DuckDB Is Really Waiting

"Started" is not enough. A process can be started and still not have opened its pipe.

The producer looks inside the kernel: `/proc/<duckdb pid>/wchan` names what the process is blocked on.

```text
wchan = wait_for_partner     → duckdb is inside open() on rows.pipe, waiting for a writer: start bcp
```

It checks every 10 ms. If it does not see it within 3 seconds, it logs that and starts bcp anyway, so a setup problem is visible, not hidden.

## Proof in Every Run

Every run records a `pipeTrace`: who held `rows.pipe`, and when, in milliseconds (illustrative):

```text
   0 ms  duckdb waits on rows.pipe
  12 ms  bcp: holds rows.pipe
 140 ms  first parquet bytes
 ...
```

When a delivery looks wrong, the trace answers the first question: was every reader there before its writer?

> **Start from the sink to the source: every reader listens before its writer speaks, or the data is lost without an error.**

---

# 8. Types Come from the Source

Text in the middle usually means guessed types.

A decimal becomes a string, a date becomes text, a code with leading zeros becomes a number.

So DuckDB does not guess. Before the query, the producer reads the source's own column types from `INFORMATION_SCHEMA.COLUMNS` and maps them:

| SQL Server | DuckDB |
| --- | --- |
| `int`, `bigint`, `smallint` | `INTEGER`, `BIGINT`, `SMALLINT` |
| `decimal`, `numeric`, `money` | `DOUBLE` |
| `datetime`, `datetime2` | `TIMESTAMP` |
| `char`, `varchar`, `nvarchar`, … | `VARCHAR` |
| anything else | the extract fails |

`DOUBLE` instead of `DECIMAL` is deliberate: analytic sums are fast, and 128-bit decimals made our queries about 3× slower.

A date stored as `yyyymmdd` text is delivered as `BIGINT`, so a date filter can still skip row groups.

Text is quoted inside the SQL itself, with inner quotes doubled, so a `|` or a `"` inside a product name cannot break a row:

```sql
SELECT [C], '"' + REPLACE(CAST([Nm] AS nvarchar(max)), '"', '""') + '"' AS [Nm], ...
```

DuckDB then reads the pipe with `auto_detect=false` and the exact column list.

> **Types travel next to the data, from the source, never guessed from the text.**

---

# 9. Row Groups Sized from Column Widths

The first paper showed why row groups matter to the reader.

Here they matter to the writer too: DuckDB holds one row group in memory while it builds it.

So the row-group size is the memory knob.

The producer computes it from the column types before the first row:

```text
row width   = Σ type width   (INTEGER 4, BIGINT 8, TIMESTAMP 8, VARCHAR 16 + declared length, …)
rows per RG = 100 MB ÷ (row width × 0.9)
```

The 0.9 is measured, not guessed: DuckDB's flushed buffer was about 0.9 of the width estimate (32 MB estimated, 28.7 MB flushed).

A wide table gets fewer rows per row group, a narrow one more. Both use about the same memory.

> **The row-group size is both a reader's skipping unit and the writer's memory limit.**

---

# 10. Upload in Chunks

The Parquet never exists as a whole file on our side.

Node reads `parquet.pipe` and sends it to a resumable upload session, 8 MB at a time:

```text
open session ──► PUT bytes 0–8M ──► PUT 8M–16M ──► … ──► PUT last chunk + total size
                   308 continue        308 continue           object appears
```

Until the last chunk is sent, the bucket shows nothing.

The object appears only when the last chunk arrives, carrying the total size.

## The Bucket Is the One Thing That Scales

Everything on our side is small and fixed: one pipe buffer, one row group, one chunk.

Everything that grows goes to the bucket.

And the bucket is built for exactly that:

| | Our side | The bucket (GCS / S3) |
| --- | --- | --- |
| Memory | fixed, ~1 GB | not our problem |
| Disk | zero | effectively unlimited |
| One object | — | up to 5 TB |
| Durability | lost when the job ends | replicated, built to keep data for years |

A billion sales lines would be roughly 12 GB of Parquet (an estimate from the 52.4M-row run: 616 MB). That is far below the size of one object, let alone a bucket.

So the question "will it fit?" has only one place to be asked, and there the answer is always yes.

We trust the bucket at the end of the pipe, and we only keep what is in flight.

> **The bucket is the only place the whole file ever exists.**

---

## Part III — A Resilient Middle

The two ends are endless and reliable. The middle is small, and it is where things break.

A stream of a billion rows runs for hours. The longer it runs, the more of these it will meet:

```text
SQL Server ──► [ link drops · bcp fails · duckdb fails · pipe hangs · chunk lost · job cancelled ] ──► bucket
                                      everything in the middle
```

So everything in the middle must be resilient, in four ways:

| Promise | Meaning |
| --- | --- |
| **Never partial** | a failure anywhere leaves no file in the bucket |
| **Never stuck** | no stage waits forever on a partner that is gone |
| **Survive the network** | a lost chunk is resumed, not restarted |
| **Always restartable** | a failed or cancelled run leaves nothing to clean, so the next run simply starts again |

The next three chapters are these promises in code.

# 11. All or Nothing

A stuck or failed download must not leave half a file for the next step to read.

So the last chunk is sent only when everything succeeded:

```text
bcp exit 0  AND  duckdb exit 0  AND  no upload error
        ↓ yes                                ↓ no
send last chunk → file appears       delete the upload session → nothing appears
```

A process killed by a signal exits without a code. That counts as a failure too, never as a complete file.

Locally, the same rule is a `.partial` file, renamed only when complete.

> **A delivery exists only when it is complete.**

---

# 12. No Stage Waits Forever

The careful setup (chapter 7) makes sure every reader is there before its writer.

The opposite danger comes at the end: a reader waiting for a writer that is already gone.

A reader of a named pipe waits until a writer opens it, and then until the writer closes it. If the writer never comes, the reader waits forever.

Two cases would hang without care:

* **bcp exits without ever opening its output**: zero rows, or a failed login. DuckDB would wait on `rows.pipe` for a writer that never
  comes. So after bcp exits, the producer keeps opening and closing `rows.pipe`, every 200 ms, until DuckDB exits: DuckDB reads end of file
  whenever it gets there.
* **one side fails**: the other is stopped, and `parquet.pipe` is released the same way, so node is not left waiting on a dead partner.

```text
bcp gone, duckdb waiting  → open + close rows.pipe     → duckdb reads end of file → exits
duckdb failed             → stop bcp, release the pipe → node reads end of file   → nothing is published
```

Ending is part of the setup too: every stage must always be able to see the end of its stream.

> **Every reader must always reach an end of file, even when its writer never came.**

---

# 13. Retries and Cancellation

A long download meets the network many times.

A chunk that fails or times out (120 s) is not sent again blindly. The producer asks the session how many bytes it really has, and continues from there:

```text
PUT chunk ──✗──► probe: "bytes */*" ──► Range: 0–41,943,039 ──► resend from 41,943,040
```

Up to three attempts per chunk, then the run fails and publishes nothing.

A run can also be cancelled. Cloud Run sends `SIGTERM` and allows about ten seconds.

In that time the producer stops bcp and DuckDB, deletes the upload session, and logs how far it got.

> **Resume from what the bucket confirms, and leave nothing when stopped.**

---

## Part IV — Operating It

# 14. Watching a Stream Live

A stream that can run for ten minutes must be visible while it runs, not only after.

Each run writes one JSONL log to the bucket, rewritten as it goes, at most once a second:

| Event | What it shows |
| --- | --- |
| `start` | the query, the target object, row width, rows per row group |
| `rowGroup` | each row group as DuckDB flushes it |
| `progress` | every 10 s: MB and rows read → row groups and MB uploaded, memory and CPU per process |
| `done` | rows, bytes, row groups, peak memory, the `pipeTrace` |
| `cancelled`, `failed` | how far it got, the DuckDB error, the bcp tail |

A typical progress line:

```text
in 412 MB / 3100000 rows -> 4 rg out (96 MB, uploaded 88 MB) | mem duckdb 380 MB, bcp 12 MB, node 210 MB
```

Memory is sampled from `/proc` for every process. That is how we know it stays flat.

These are the measured runs of our four fact tables, starting over from 2025-01-01, on 1 vCPU and 2 GiB:

| Table | Rows | Row groups | Parquet | Time |
| --- | ---: | ---: | ---: | ---: |
| Price changes (small) | 216K | 1 | 1 MB | 3 s |
| Sales headers | 6.5M | 11 | 101 MB | 2 min |
| Daily prices | 11.5M | 37 | 167 MB | 2 min |
| Sales lines | 52.4M | 55 | 616 MB | 10.5 min |

Peak memory, for the smallest and the largest alike: DuckDB at most 450 MB, node about 250 MB, bcp 12 MB.

The limit is not memory and not CPU. It is the link to SQL Server: 7–13 MB/s of text.

At the same rate, a billion such rows would take about three and a half hours (an estimate from the 52.4M-row run): longer, with the same memory, never stuck.

> **Flat memory is not a promise; it is a measured line in every log.**

---

# 15. Crash Logs Versus the Big Log

A run can end in two ways.

It finishes, and we want to read everything it did, in one place.

Or it is killed in the middle: out of memory, a timeout, a cancel. Then we want to know how far it got, and why it stopped.

These two needs pull in opposite directions.

## The Big Log: Everything, Once, at the End

The big log collects every logger of the run in memory, and writes them as one file when the run ends.

```text
run ──────────────────────────────────────────► end
     events kept in memory                      write bigLog.json  (one PUT)
```

It is complete, rich, and cheap: one write per run.

But it is written at the end. If the run never reaches the end, the big log is never written.

```text
run ──────────────────────✗ killed
     events kept in memory   gone with the process
                             bigLog.json: never written
```

The big log is lost exactly when it is needed most.

## Crash Logs: Every Event, at Once

A crash log writes each event the moment it happens, as its own small file:

```text
run ──●────●────●────●──────✗ killed
      │    │    │    │
      ▼    ▼    ▼    ▼
   crash-log-0001 … 0004    survive the process
```

When the run ends well, the big log is saved, and the crash logs are deleted.

So crash logs that remain tell their own story: **they belong to a run that never finished**, and the last one shows where it stopped.

The price: one write per event, and many small files while the run is alive.

## Reading a Log That Has No End

A finished run ends with `done`, `failed` or `cancelled`.

A cancel still gets its last line: Cloud Run sends `SIGTERM` and allows about ten seconds, and the producer uses them to log how far it got.

An out-of-memory kill gets nothing: the process is gone at once.

So the admin view reads the log itself:

```text
last event   done / failed / cancelled     → that is the status
no end, and the file stopped changing > 2 minutes ago   → stale: the run died
no end, and the file is still changing  → running
```

A log that stops without an end is the crash log.

> **Write the log as the run goes: a log written at the end is lost exactly when it is needed.**

---

# 16. What We Learned

| Chapter | Chapter name | What we learned |
| ------: | ------------ | --------------- |
| **1** | **One Query, Billions of Rows** | The obvious download keeps the table somewhere before the bucket. |
| **2** | **It Will Get Stuck** | Every value becomes an object to build, convert and collect; memory or disk that grows with the table gets stuck, we cannot know when. |
| **3** | **A Bigger Machine Only Moves the Wall** | Both ends are endless; only the middle is bounded: a pipe, not a tank. On Cloud Run, disk is memory. |
| **4** | **Why the Parquet Footer Is at the End** | The footer is written last, so a Parquet file is built in one pass and can stream; the reader reads it first. |
| **5** | **Three Processes, Two Pipes** | Named pipes stream the whole table; no value becomes an object, and only a little of it exists at any moment. |
| **6** | **How the Middle Says Stop** | Every stage pulls; a full pipe and a closed TCP window stop SQL Server; every buffer has a fixed bound. |
| **7** | **Careful Setup: From the Sink to the Source** | Start every reader before its writer; the wrong order loses rows silently, with every process green. |
| **8** | **Types Come from the Source** | Column types come from `INFORMATION_SCHEMA`, never guessed from text. |
| **9** | **Row Groups Sized from Column Widths** | The row-group size is the writer's memory limit. |
| **10** | **Upload in Chunks** | The bucket is the only place the whole file exists, and the one thing that scales: it is never too big for it. |
| **11** | **All or Nothing** | The last chunk is sent only when every process succeeded. |
| **12** | **No Stage Waits Forever** | Every reader must reach an end of file, even when its writer never came. |
| **13** | **Retries and Cancellation** | Resume from the confirmed offset; a cancelled run leaves nothing. |
| **14** | **Watching a Stream Live** | Live logs prove memory stays flat; the source link is the limit. |
| **15** | **Crash Logs Versus the Big Log** | A big log is complete but lost in a crash; crash logs survive it; a log with no end is the crash log. |

> **It is only a matter of size until the design makes size a matter of time.**

---

# References

1. **Why Parquet Structure Matters for Fast Queries**
   `../parquet/paper.md`
   Row groups and footer statistics.

2. **Faster Parquet with a Column Cache**
   `../faster-parquet-cache/paper.md`
   Reading the Parquet this paper writes.

3. **Microsoft — bcp utility**
   `https://learn.microsoft.com/en-us/sql/tools/bcp-utility`
   Bulk-copy rows out of SQL Server with `queryout`.

4. **DuckDB — COPY statement**
   `https://duckdb.org/docs/stable/sql/statements/copy`
   `COPY … TO … (FORMAT PARQUET, ROW_GROUP_SIZE …)`.

5. **DuckDB — CSV import**
   `https://duckdb.org/docs/stable/data/csv/overview`
   `read_csv` with explicit columns and `auto_detect=false`.

6. **Google Cloud — Resumable uploads**
   `https://cloud.google.com/storage/docs/resumable-uploads`
   Uploading one object in chunks, and resuming from the confirmed offset.

7. **Google Cloud — Storage quotas and limits**
    `https://cloud.google.com/storage/quotas`
    A single object can be up to 5 TiB; a bucket has no total size limit.

8. **Google Cloud Run — Container runtime contract**
   `https://cloud.google.com/run/docs/container-contract#filesystem`
   The in-memory file system: a job's local disk counts against its memory.

9. **Linux — fifo(7)**
   `https://man7.org/linux/man-pages/man7/fifo.7.html`
   Named pipes: opening blocks until both ends are open, except a read-write open, which never blocks on Linux.

10. **Linux — pipe(7)**
    `https://man7.org/linux/man-pages/man7/pipe.7.html`
    Pipe capacity (65,536 bytes by default), and how `write()` blocks on a full pipe and `read()` on an empty one.

11. **Python — gc module**
   `https://docs.python.org/3/library/gc.html`
   The generational cyclic garbage collector and its allocation thresholds.
