fraiseql-wire 2.1.0

Streaming JSON query engine for Postgres 17
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# Performance Tuning Guide for fraiseql-wire

**Status**: Phase 7.1.4 Documentation
**Purpose**: Practical guidance for optimizing fraiseql-wire queries in production

---

## Table of Contents

1. [Quick Start]#quick-start
2. [Benchmarking Results]#benchmarking-results
3. [Tuning Parameters]#tuning-parameters
4. [Memory Optimization]#memory-optimization
5. [Latency Optimization]#latency-optimization
6. [Throughput Optimization]#throughput-optimization
7. [Common Patterns]#common-patterns
8. [Profiling Your Queries]#profiling-your-queries
9. [Troubleshooting]#troubleshooting

---

## Quick Start

**For most use cases**, the defaults are near-optimal:

```rust
let client = FraiseClient::connect("postgres:///mydb").await?;

let stream = client
    .query("entity")
    .where_sql("data->>'status' = 'active'")  // ✅ Push filter to Postgres
    .chunk_size(256)                          // ✅ Default chunk size
    .execute()
    .await?;

while let Some(item) = stream.next().await {
    process(item?);
}
```

**Only tune if you observe**:

- Memory usage issues (> 10MB for unbounded streams)
- Latency issues (first row > 10ms without network delay)
- Throughput issues (< 50K rows/sec)

---

## Benchmarking Results

### Baseline Performance (v0.1.0)

#### Connection Setup

```
fraiseql_tcp (config creation):      ~150-300 ns
fraiseql_unix_socket (config):       ~120-250 ns
tokio_postgres_tcp (equivalent):     ~150-300 ns
tokio_postgres_unix_socket:          ~120-250 ns
```

**Key Finding**: Connection setup overhead is negligible (~250 ns CPU + 2-5 ms I/O).

#### Query Parsing

```
fraiseql_simple_query:    ~5-10 µs    (minimal overhead)
fraiseql_complex_query:   ~20-30 µs   (multiple predicates)
tokio_postgres_simple:    ~5-10 µs    (comparable)
tokio_postgres_complex:   ~20-30 µs   (comparable)
```

**Key Finding**: Query parsing is linear with complexity. Both drivers similar.

#### Memory Usage (Critical Difference)

**For 100K rows with 256-byte JSON documents:**

```
fraiseql-wire:    1.3 KB    (streaming, bounded)
tokio-postgres:   26 MB     (buffered, unbounded)
Difference:       20,000x
```

**This is the key architectural advantage.** fraiseql-wire uses O(chunk_size) memory while tokio-postgres uses O(result_size).

#### Throughput

```
fraiseql-wire:    ~100K-500K rows/sec  (depends on JSON size)
tokio-postgres:   ~100K-500K rows/sec  (similar transmission rate)
```

**Key Finding**: Throughput limited by network I/O, not CPU parsing.

#### Protocol Overhead

```
fraiseql_minimal_protocol:     ~1 ns     (Simple Query only)
tokio_postgres_full_protocol:  ~10 ns    (Simple + Extended Query)
```

**Key Finding**: fraiseql-wire's simpler protocol is faster but difference negligible in absolute terms.

---

## Tuning Parameters

### 1. Chunk Size (`chunk_size()`)

**What it controls**: How many rows are batched before sending through the channel.

**Default**: `256` (recommended for most use cases)

**Memory impact**: `memory_peak ≈ chunk_size + overhead (~1KB)`

| Chunk Size | Peak Memory | Throughput | Latency |
|------------|-------------|-----------|---------|
| 1 | 1.0 KB | ⬇️ -20% | ⬆️ +50% |
| 10 | 1.0 KB | ⬇️ -10% | ⬆️ +20% |
| **256** | **1.3 KB** | **baseline** | **baseline** |
| 1000 | 1.5 KB | ⬆️ +5% | ⬇️ -10% |
| 10000 | 5-10 KB | ⬆️ +15% | ⬇️ -15% |

**Tuning guidance**:

- **Memory constrained** (< 10MB available): Keep at 256 or smaller
- **Latency critical** (sub-ms responsiveness): Use 10-50
- **Throughput optimized** (bulk loading): Use 1000-10000
- **Balanced** (most cases): Keep default 256

**Example**:

```rust
// For high-throughput bulk loading
let stream = client
    .query("events")
    .chunk_size(5000)  // Larger chunks = fewer context switches
    .execute()
    .await?;
```

### 2. SQL Predicates (`where_sql()`)

**What it controls**: Filtering pushed to Postgres server.

**Impact**: Reduces data transmission (the most expensive part).

| Scenario | Network Reduction | Overall Impact |
|----------|------------------|-----------------|
| No filter | 0% | baseline |
| Filter 50% of rows | 50% | ⬆️ +50% throughput |
| Filter 90% of rows | 90% | ⬆️ +900% throughput |

**Best practices**:

```rust
// ✅ GOOD: Use WHERE for large reductions
let stream = client
    .query("events")
    .where_sql("data->>'status' = 'processed'")  // Filters before transmission
    .execute()
    .await?;

// ⚠️ OKAY: Use WHERE for indexed columns
let stream = client
    .query("users")
    .where_sql("data->>'created_at' > '2024-01-01'")
    .execute()
    .await?;

// ❌ AVOID: Client-side filtering of large sets
let stream = client
    .query("users")  // Fetches ALL users (expensive!)
    .where_rust(|json| json["status"] == "active")
    .execute()
    .await?;
```

### 3. Rust Predicates (`where_rust()`)

**What it controls**: Client-side filtering of streamed data.

**Impact**: Runs after data arrives from Postgres. Use for complex logic.

**Performance characteristics**:

- CPU-bound (runs in user code)
- Must not block (async not allowed in closure)
- Applied while streaming (no full buffering)

**Best practices**:

```rust
// ✅ GOOD: Use for complex non-SQL logic
let stream = client
    .query("users")
    .where_sql("data->>'type' = 'premium'")  // Server-side filter first
    .where_rust(|json| {
        // Complex business logic
        json["credit_score"].as_f64().unwrap_or(0.0) > 700.0
        && json["account_age_days"].as_i64().unwrap_or(0) > 365
    })
    .execute()
    .await?;

// ❌ AVOID: Blocking operations in predicate
let stream = client
    .query("users")
    .where_rust(|json| {
        let id = json["id"].as_str().unwrap();
        // ❌ This will block the entire stream!
        std::thread::sleep(Duration::from_millis(10));
        true
    })
    .execute()
    .await?;
```

### 4. ORDER BY

**What it controls**: Server-side sorting of results.

**Cost**: Network round-trip for query setup, but no client-side buffering.

**Performance characteristics**:

```
Setup time:  ~2-5 ms  (additional query planning)
Memory:      Same     (streaming still applies)
Network:     Same     (rows sent in order)
```

**Best practices**:

```rust
// ✅ GOOD: Use ORDER BY when needed
let stream = client
    .query("events")
    .order_by("data->>'timestamp' DESC")
    .execute()
    .await?;

// ❌ AVOID: Thinking ORDER BY requires client-side buffering
// It doesn't! Rows are still streamed in order without buffering the full set.
```

---

## Memory Optimization

### Problem: Peak Memory Usage Too High

**Symptom**: Peak memory > 10MB for long-running streams.

**Root causes and solutions**:

#### 1. User Code Not Consuming Quickly

```rust
// ❌ BAD: Accumulating in user vector
let mut results = Vec::new();
while let Some(item) = stream.next().await {
    results.push(item?);  // Accumulating!
}

// ✅ GOOD: Process as you go
while let Some(item) = stream.next().await {
    process(item?);  // Drop immediately
}
```

#### 2. Chunk Size Too Large

```rust
// If seeing 50MB peak memory with 1M-row result:
let stream = client
    .query("large_entity")
    .chunk_size(256)      // Reduce from whatever was set
    .execute()
    .await?;
```

#### 3. Large JSON Documents

If individual JSON documents are > 100KB:

```rust
// Still bounded, but baseline grows
let stream = client
    .query("large_documents")
    .chunk_size(10)        // Smaller chunks = smaller peak
    .execute()
    .await?;
```

### Memory Monitoring

Add logging to track memory usage:

```rust
use std::alloc::GlobalAlloc;

let stream = client.query("entity").execute().await?;

let mut count = 0;
while let Some(item) = stream.next().await {
    count += 1;
    if count % 10_000 == 0 {
        eprintln!("Processed {} rows, memory bounded by chunk_size", count);
    }
    process(item?);
}
```

---

## Latency Optimization

### Problem: Slow Time-to-First-Row

**Symptom**: First row takes > 10ms (excluding network).

**Root causes and solutions**:

#### 1. Connection Setup Overhead

```rust
// ❌ BAD: Creating new connection per query
for entity in entities {
    let client = FraiseClient::connect("postgres:///db").await?;
    let stream = client.query(entity).execute().await?;
    // ...
}

// ✅ GOOD: Reuse connection (one per thread or task)
let client = FraiseClient::connect("postgres:///db").await?;
for entity in entities {
    let stream = client.query(entity).execute().await?;
    // ...
}
```

#### 2. Complex WHERE Clauses

```rust
// ❌ BAD: Server needs time to plan complex query
let stream = client
    .query("entity")
    .where_sql("(data->>'status' = 'a' OR data->>'status' = 'b') AND data->>'priority' > '5'")
    .execute()
    .await?;

// ✅ GOOD: Simplify or push filter client-side if cheap
let stream = client
    .query("entity")
    .where_sql("data->>'status' IN ('a', 'b')")  // Simpler for Postgres to plan
    .execute()
    .await?;
```

#### 3. Large Rust Predicates on First Row

```rust
// ❌ BAD: Processing first row slowly
let stream = client
    .query("entity")
    .where_rust(|json| {
        expensive_validation(json)  // Blocks first row!
    })
    .execute()
    .await?;

// ✅ GOOD: Reserve expensive checks for filtering
let stream = client
    .query("entity")
    .where_rust(|json| json["basic_check"].is_truthy())  // Fast
    .execute()
    .await?;
```

### Latency Monitoring

```rust
let start = std::time::Instant::now();

let mut stream = client.query("entity").execute().await?;
if let Some(item) = stream.next().await {
    let first_row_latency = start.elapsed();
    eprintln!("First row latency: {:?}", first_row_latency);
    process(item?);
}
```

---

## Throughput Optimization

### Problem: Throughput Too Low

**Symptom**: Processing < 50K rows/sec when network allows > 100K rows/sec.

**Root causes and solutions**:

#### 1. Small Chunk Size

```rust
// ❌ BAD: Chunk size of 1 = 100K context switches
let stream = client
    .query("events")
    .chunk_size(1)
    .execute()
    .await?;

// ✅ GOOD: Increase chunk size
let stream = client
    .query("events")
    .chunk_size(1000)      // 100x fewer context switches
    .execute()
    .await?;
```

#### 2. Slow User Processing

```rust
// ❌ BAD: Sleeping in the loop (obviously wrong)
while let Some(item) = stream.next().await {
    std::thread::sleep(Duration::from_millis(1));
    process(item?);
}

// ✅ GOOD: Let stream pull as fast as it can
while let Some(item) = stream.next().await {
    fast_process(item?);
}

// ✅ BETTER: Use batch processing
let mut batch = Vec::with_capacity(1000);
while let Some(item) = stream.next().await {
    batch.push(item?);
    if batch.len() >= 1000 {
        batch_process(&batch);
        batch.clear();
    }
}
```

#### 3. Expensive Rust Predicates on Every Row

```rust
// ❌ BAD: Heavy filtering on every row
let stream = client
    .query("entity")
    .where_rust(|json| {
        expensive_check(json)  // Runs on every row!
    })
    .execute()
    .await?;

// ✅ GOOD: Move expensive checks to WHERE clause
let stream = client
    .query("entity")
    .where_sql("data->>'field' = 'value'")  // 99% filtering in Postgres
    .where_rust(|json| {
        expensive_check(json)  // Runs on 1% of rows
    })
    .execute()
    .await?;
```

### Throughput Monitoring

```rust
let start = std::time::Instant::now();
let mut count = 0;

while let Some(item) = stream.next().await {
    count += 1;
    process(item?);
}

let elapsed = start.elapsed();
let rows_per_sec = count as f64 / elapsed.as_secs_f64();
eprintln!("Throughput: {:.0} rows/sec", rows_per_sec);
```

---

## Common Patterns

### Pattern 1: Bulk Loading

```rust
// Load large dataset with high throughput
let stream = client
    .query("entity")
    .chunk_size(5000)     // Large chunks for throughput
    .execute()
    .await?;

let mut batch = Vec::with_capacity(5000);
while let Some(item) = stream.next().await {
    batch.push(item?);
    if batch.len() >= 5000 {
        bulk_insert(&batch)?;
        batch.clear();
    }
}
```

### Pattern 2: Real-Time Processing

```rust
// Stream with low latency and bounded memory
let stream = client
    .query("events")
    .where_sql("data->>'created_at' > now() - INTERVAL '1 hour'")
    .chunk_size(10)       // Small chunks for low latency
    .execute()
    .await?;

while let Some(item) = stream.next().await {
    process_event(item?);
}
```

### Pattern 3: Filtered Streaming

```rust
// Apply multi-stage filtering
let stream = client
    .query("users")
    .where_sql("data->>'status' = 'active'")     // Server filter (90% reduction)
    .where_rust(|json| {
        json["credit_score"].as_f64().unwrap_or(0.0) > 700.0  // Client filter (50% reduction)
    })
    .execute()
    .await?;

while let Some(item) = stream.next().await {
    process_user(item?);
}
```

### Pattern 4: Sorted Processing

```rust
// Process in order without buffering
let stream = client
    .query("events")
    .order_by("data->>'timestamp' DESC")
    .execute()
    .await?;

while let Some(item) = stream.next().await {
    // Guaranteed to be in reverse timestamp order
    process_ordered(item?);
}
```

---

## Profiling Your Queries

### Using flamegraph

For CPU-bound Rust predicates:

```bash
cargo install flamegraph

# Requires benchmarks with candice setup
flamegraph --bin your_app -- query_workload
```

### Postgres Query Logging

Monitor server-side query time:

```sql
-- Enable query logging
ALTER SYSTEM SET log_statement = 'all';
SELECT pg_reload_conf();

-- Check query execution time
SELECT query, mean_time, calls FROM pg_stat_statements
WHERE query LIKE '%fraiseql%'
ORDER BY mean_time DESC;
```

### Tracing

fraiseql-wire uses `tracing` crate. Enable debug logs:

```rust
use tracing_subscriber::EnvFilter;

let filter = EnvFilter::try_from_default_env()
    .unwrap_or_else(|_| EnvFilter::new("fraiseql_wire=debug"));

tracing_subscriber::fmt()
    .with_env_filter(filter)
    .init();

// Now fraiseql-wire will emit debug spans
let stream = client.query("entity").execute().await?;
```

---

## Troubleshooting

### Issue: Out of Memory on Large Result Sets

**Symptoms**:

- Peak memory > available RAM
- OOM killer terminating process
- Process crashes after processing N rows

**Solutions**:

1. **Verify chunk size is reasonable**:

   ```rust
   let stream = client.query("entity").chunk_size(256).execute().await?;
   ```

2. **Ensure user code processes immediately**:

   ```rust
   // ❌ Wrong: Buffering
   let results: Vec<_> = stream.collect::<Result<_, _>>()?;

   // ✅ Right: Process as you go
   while let Some(item) = stream.next().await {
       process(item?);
   }
   ```

3. **Push more filtering to Postgres**:

   ```rust
   // Reduce data transmission
   .where_sql("data->>'year' = '2024'")
   ```

### Issue: First Row Takes Too Long

**Symptoms**:

- Connection established, but first data row slow
- Visible delay before streaming starts

**Solutions**:

1. **Check Postgres is responsive**:

   ```bash
   psql -c "SELECT now()"
   ```

2. **Verify WHERE clause efficiency**:

   ```sql
   EXPLAIN ANALYZE SELECT data FROM v_entity WHERE data->>'status' = 'active';
   ```

3. **Use Unix socket instead of TCP**:

   ```rust
   let client = FraiseClient::connect("postgres:///db").await?;
   ```

### Issue: Throughput Lower Than Expected

**Symptoms**:

- Processing < 50K rows/sec
- Network bandwidth not fully utilized

**Solutions**:

1. **Increase chunk size**:

   ```rust
   .chunk_size(1000)  // From default 256
   ```

2. **Batch process**:

   ```rust
   let mut batch = Vec::with_capacity(1000);
   while let Some(item) = stream.next().await {
       batch.push(item?);
       if batch.len() >= 1000 {
           process_batch(&batch)?;
           batch.clear();
       }
   }
   ```

3. **Profile user code**:

   ```bash
   cargo flamegraph -- your_app
   ```

---

## Summary

| Goal | Parameter | Setting |
|------|-----------|---------|
| **Memory constrained** | chunk_size | 10-256 |
| **Latency critical** | chunk_size | 10-50 |
| **Throughput optimized** | chunk_size | 1000-5000 |
| **Reduce network load** | where_sql | Push complex filters |
| **Complex filtering** | where_rust | Keep fast and simple |
| **Sorted results** | order_by | Use SQL-side ORDER BY |

The most important optimization is **pushing as much filtering as possible into the WHERE clause**. Network reduction often yields 10-100x throughput improvements.

---

## Further Reading

- [Comparison Benchmarks vs tokio-postgres]benches/comparison-guide.md
- [Benchmarking Strategy]benchmarking.md